List only the sources an account uses on the source-priority page

The read and save of /api/auth/me/source-priority now carry inUse: the
ranked sources the account has connected or holds at least one
measurement from, one index probe per source. The settings page lists
only those, hides a metric nothing delivers, and opens one metric group
at a time, the first by default, with the winning source named on each
collapsed line. The ladders stay whole: moving a source swaps it with
its nearest listed neighbour, so a hidden source keeps its slot.
This commit is contained in:
Marc-André Bombeck committed 2026-10-08 20:40:39 +02:00
1 parent c816946140
commit 51374274aa
15 files changed
+956 -1475

No files matched your search

@@ -0,0 +1,70 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/db", () => ({
prisma: {
measurement: { findFirst: vi.fn() },
user: { findUnique: vi.fn() },
withingsConnection: { findUnique: vi.fn() },
whoopConnection: { findUnique: vi.fn() },
fitbitConnection: { findUnique: vi.fn() },
googleHealthConnection: { findUnique: vi.fn() },
},
}));
import { prisma } from "@/lib/db";
import {
getSourcesInUse,
RANKABLE_SOURCES,
} from "@/lib/integrations/sources-in-use";
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(prisma.user.findUnique).mockResolvedValue(null);
vi.mocked(prisma.withingsConnection.findUnique).mockResolvedValue(null);
vi.mocked(prisma.whoopConnection.findUnique).mockResolvedValue(null);
vi.mocked(prisma.fitbitConnection.findUnique).mockResolvedValue(null);
vi.mocked(prisma.googleHealthConnection.findUnique).mockResolvedValue(null);
});
describe("getSourcesInUse", () => {
it("lists a source the account holds data from", async () => {
vi.mocked(prisma.measurement.findFirst).mockImplementation(((args: {
where: { source: string };
}) =>
Promise.resolve(
args.where.source === "MANUAL" ? { id: "m1" } : null,
)) as never);
expect(await getSourcesInUse("u1")).toEqual(["MANUAL"]);
});
it("lists a connected integration that has not delivered yet", async () => {
vi.mocked(prisma.measurement.findFirst).mockResolvedValue(null);
vi.mocked(prisma.withingsConnection.findUnique).mockResolvedValue({
userId: "u1",
} as never);
vi.mocked(prisma.user.findUnique).mockResolvedValue({
polarAccessTokenEncrypted: "x",
ouraAccessTokenEncrypted: null,
stravaAccessTokenEncrypted: null,
} as never);
const inUse = await getSourcesInUse("u1");
expect(inUse).toContain("WITHINGS");
expect(inUse).toContain("POLAR");
expect(inUse).not.toContain("OURA");
});
it("lists nothing for an account with no data and no connection", async () => {
vi.mocked(prisma.measurement.findFirst).mockResolvedValue(null);
expect(await getSourcesInUse("u1")).toEqual([]);
});
it("probes every rankable source exactly once", async () => {
vi.mocked(prisma.measurement.findFirst).mockResolvedValue(null);
await getSourcesInUse("u1");
expect(prisma.measurement.findFirst).toHaveBeenCalledTimes(
RANKABLE_SOURCES.length,
);
});
});
+78
View File
@@ -0,0 +1,78 @@
import type { MeasurementSource } from "@/generated/prisma/client";
import { prisma } from "@/lib/db";
import { DEFAULT_SOURCE_PRIORITY } from "@/lib/validations/source-priority";
/**
* Every source a source-priority ladder can rank, in a stable order.
*
* Derived from the default ladders rather than listed by hand, so a source
* added to a ladder is probed without a second edit here.
*/
export const RANKABLE_SOURCES: readonly MeasurementSource[] = Array.from(
new Set(Object.values(DEFAULT_SOURCE_PRIORITY).flat()),
) as MeasurementSource[];
/**
* The rankable sources this account actually has: a source it holds at least
* one measurement from, or an integration it has connected that has not
* delivered yet.
*
* The Settings ladder lists only these. Ranking a source the person has never
* used decides nothing, and ten of them per metric buried the two that do.
* The ladders themselves stay whole: hidden sources keep their slot, so a
* source that starts delivering later lands where the ladder already put it.
*
* Each data probe is a `LIMIT 1` on the `(userId, source, measuredAt)` index,
* so the cost is one index lookup per rankable source, not a scan.
*/
export async function getSourcesInUse(
userId: string,
): Promise<MeasurementSource[]> {
const [withData, user, withings, whoop, fitbit, googleHealth] =
await Promise.all([
Promise.all(
RANKABLE_SOURCES.map((source) =>
prisma.measurement
.findFirst({ where: { userId, source }, select: { id: true } })
.then((row) => (row ? source : null)),
),
),
prisma.user.findUnique({
where: { id: userId },
select: {
polarAccessTokenEncrypted: true,
ouraAccessTokenEncrypted: true,
stravaAccessTokenEncrypted: true,
},
}),
prisma.withingsConnection.findUnique({
where: { userId },
select: { userId: true },
}),
prisma.whoopConnection.findUnique({
where: { userId },
select: { userId: true },
}),
prisma.fitbitConnection.findUnique({
where: { userId },
select: { userId: true },
}),
prisma.googleHealthConnection.findUnique({
where: { userId },
select: { userId: true },
}),
]);
const inUse = new Set<MeasurementSource>(
withData.filter((s): s is MeasurementSource => s !== null),
);
if (withings) inUse.add("WITHINGS");
if (whoop) inUse.add("WHOOP");
if (fitbit) inUse.add("FITBIT");
if (googleHealth) inUse.add("GOOGLE_HEALTH");
if (user?.polarAccessTokenEncrypted) inUse.add("POLAR");
if (user?.ouraAccessTokenEncrypted) inUse.add("OURA");
if (user?.stravaAccessTokenEncrypted) inUse.add("STRAVA");
return RANKABLE_SOURCES.filter((s) => inUse.has(s));
}
+18 -2
View File
@@ -9,6 +9,7 @@ import { z } from "zod/v4";
import type { ZodOpenApiObject } from "zod-openapi";
import { notificationPrefsSchema } from "@/lib/validations/notification-prefs";
import { sourcePrioritySchema } from "@/lib/validations/source-priority";
import { measurementSourceEnum } from "@/lib/validations/measurement";
import { modulePrefsPatchSchema } from "@/lib/validations/modules";
import { MODULE_KEYS } from "@/lib/modules/registry";
import {
@@ -204,6 +205,21 @@ export const aiAccountBlock = z
"Which AI capabilities the record this session is inside has, and why not when it has none. Resolved on the server for the ACTIVE RECORD and masked to the sections the active grant opens, exactly like `modules` and `moduleAccess`; with no switch (every native request) it describes the caller's own record.",
});
/**
* The source-priority read and save both echo the resolved ladders plus
* `inUse`: the ranked sources the account has connected or holds data from.
* Context for an editor, never part of the stored shape (the PUT body stays
* `SourcePriority`).
*/
const sourcePriorityResolved = sourcePrioritySchema
.extend({
inUse: z.array(measurementSourceEnum).meta({
description:
"Ranked sources this account has connected or holds at least one measurement from, in ladder-catalogue order. Read-only; an editor may list only these while the ladders keep every source.",
}),
})
.meta({ id: "ResolvedSourcePriority" });
const moduleMapEnvelopeInner = z
.object({ modules: moduleMapResolved, updatedAt: updatedAtTokenField })
.meta({ id: "ModulesResponse" });
@@ -1425,7 +1441,7 @@ export const profilePaths: NonNullable<ZodOpenApiObject["paths"]> = {
content: {
"application/json": {
schema: dataEnvelope(
sourcePrioritySchema,
sourcePriorityResolved,
"GetSourcePriorityResponse",
),
},
@@ -1449,7 +1465,7 @@ export const profilePaths: NonNullable<ZodOpenApiObject["paths"]> = {
content: {
"application/json": {
schema: dataEnvelope(
sourcePrioritySchema,
sourcePriorityResolved,
"PutSourcePriorityResponse",
),
},