feat(nutrients): carry daily targets through backup, wipe and the API contract

Nutrient targets travel in the account-settings slice of the full
backup and are admitted code by code on restore, so an unknown code or
an out-of-range value is dropped and named while the rest come back. A
data wipe clears them. The targets route joins the OpenAPI registry,
and the regenerated contract carries the wider nutrient enums, the new
sources and the target and authority fields. Refs #1402.
This commit is contained in:
Marc-André Bombeck committed 2026-11-17 19:05:31 +01:00
1 parent 7c40ba8202
commit db0e4f9688
18 files changed
+1470 -381

No files matched your search

+1049 -169
View File
File diff suppressed because it is too large. Load diff
@@ -1,208 +0,0 @@
/**
* `POST /api/nutrients/batch` under a narrow `measurements:write` token.
*
* The credential picks the source row: a bridge token writes EXTERNAL in the
* probe, the insert and the update, counts in its own rate-limit bucket, and
* says so in the audit row; the native client keeps writing APPLE_HEALTH.
*/
import { beforeEach, describe, expect, it, vi } from "vitest";
import { NextRequest } from "next/server";
vi.mock("@/lib/db", () => ({
prisma: {
nutrientIntakeDay: {
findMany: vi.fn(),
createMany: vi.fn(),
update: vi.fn(),
},
$transaction: vi.fn(),
},
}));
vi.mock("@/lib/api-handler", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/api-handler")>();
return { ...actual, requireAuth: vi.fn() };
});
vi.mock("@/lib/modules/gate", () => ({ requireModuleEnabled: vi.fn() }));
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(),
rateLimitHeaders: () => ({}),
}));
vi.mock("@/lib/idempotency", () => ({
withIdempotency:
<Args extends unknown[]>(fn: (...args: Args) => Promise<Response>) =>
(...args: Args) =>
fn(...args),
}));
vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() }));
vi.mock("@/lib/cache/invalidate", () => ({
invalidateUserHealthContext: vi.fn(),
}));
vi.mock("next/headers", () => ({
headers: vi.fn(async () => ({ get: () => null })),
cookies: vi.fn(async () => ({
get: () => undefined,
set: () => {},
delete: () => {},
})),
}));
import { POST } from "../route";
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/api-handler";
import { auditLog } from "@/lib/auth/audit";
import { checkRateLimit } from "@/lib/rate-limit";
import { requireModuleEnabled } from "@/lib/modules/gate";
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
const USER = { id: "user-1", username: "tester", role: "USER" as const };
function asBridge() {
vi.mocked(requireAuth).mockResolvedValue({
session: { id: "t" },
user: USER,
bearerScope: MEASUREMENTS_WRITE_SCOPE,
} as never);
}
function asPhone() {
vi.mocked(requireAuth).mockResolvedValue({
session: { id: "s" },
user: USER,
} as never);
}
function post(entries: unknown[]): Promise<Response> {
return POST(
new NextRequest("http://localhost/api/nutrients/batch", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ entries }),
}),
);
}
const ENERGY = {
day: "2026-11-01",
nutrient: "energy",
unit: "kcal",
amount: 2100,
};
const PROTEIN = {
day: "2026-11-02",
nutrient: "protein",
unit: "g",
amount: 95,
};
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(checkRateLimit).mockResolvedValue({ allowed: true } as never);
vi.mocked(requireModuleEnabled).mockResolvedValue({ enabled: true });
vi.mocked(auditLog).mockResolvedValue(undefined as never);
// ENERGY's day already exists, PROTEIN's is new.
vi.mocked(prisma.nutrientIntakeDay.findMany).mockResolvedValue([
{ day: ENERGY.day, nutrient: "energy" },
] as never);
vi.mocked(prisma.nutrientIntakeDay.createMany).mockImplementation(
(async (args: { data: unknown[] }) => ({
count: args.data.length,
})) as never,
);
vi.mocked(prisma.nutrientIntakeDay.update).mockResolvedValue({} as never);
vi.mocked(prisma.$transaction).mockImplementation((async (ops: unknown[]) =>
Promise.all(ops)) as never);
});
describe("POST /api/nutrients/batch with a measurements:write token", () => {
it("asks requireAuth for the measurements:write scope", async () => {
asBridge();
await post([ENERGY]);
expect(requireAuth).toHaveBeenCalledWith(MEASUREMENTS_WRITE_SCOPE, {
writeBucket: "own",
});
});
it("writes the EXTERNAL row in the probe, the insert and the update", async () => {
asBridge();
const res = await post([ENERGY, PROTEIN]);
expect(res.status).toBe(200);
const body = (await res.json()) as {
data: { inserted: number; updated: number };
};
expect(body.data).toMatchObject({ inserted: 1, updated: 1 });
const probe = vi.mocked(prisma.nutrientIntakeDay.findMany).mock.calls[0][0];
expect(probe?.where).toMatchObject({
userId: "user-1",
source: "EXTERNAL",
});
const created = vi.mocked(prisma.nutrientIntakeDay.createMany).mock
.calls[0][0] as { data: Array<{ source: string; nutrient: string }> };
expect(created.data).toEqual([
expect.objectContaining({ nutrient: "protein", source: "EXTERNAL" }),
]);
const update = vi.mocked(prisma.nutrientIntakeDay.update).mock.calls[0][0];
expect(update.where).toEqual({
userId_day_nutrient_source: {
userId: "user-1",
day: ENERGY.day,
nutrient: "energy",
source: "EXTERNAL",
},
});
});
it("counts in the bridge bucket and names the source in the audit row", async () => {
asBridge();
await post([ENERGY]);
expect(vi.mocked(checkRateLimit).mock.calls[0][0]).toBe(
"nutrients:batch:bridge:user-1",
);
expect(auditLog).toHaveBeenCalledWith(
"nutrient.batch.ingest",
expect.objectContaining({
details: expect.objectContaining({ source: "EXTERNAL" }),
}),
);
});
it("accepts alcohol, which no HealthKit type carries", async () => {
asBridge();
const res = await post([
{ day: "2026-11-01", nutrient: "alcohol", unit: "g", amount: 24 },
]);
const body = (await res.json()) as { data: { skipped: unknown[] } };
expect(body.data.skipped).toEqual([]);
});
it("skips energy posted in kJ rather than converting it", async () => {
asBridge();
const res = await post([{ ...ENERGY, unit: "kJ", amount: 8800 }]);
const body = (await res.json()) as {
data: { skipped: Array<{ reason: string }> };
};
expect(body.data.skipped).toEqual([{ index: 0, reason: "unit_mismatch" }]);
});
});
describe("POST /api/nutrients/batch from the native client", () => {
it("keeps writing the APPLE_HEALTH row in its own bucket", async () => {
asPhone();
await post([ENERGY, PROTEIN]);
expect(vi.mocked(checkRateLimit).mock.calls[0][0]).toBe(
"nutrients:batch:user-1",
);
const probe = vi.mocked(prisma.nutrientIntakeDay.findMany).mock.calls[0][0];
expect(probe?.where).toMatchObject({ source: "APPLE_HEALTH" });
const created = vi.mocked(prisma.nutrientIntakeDay.createMany).mock
.calls[0][0] as { data: Array<{ source: string }> };
expect(created.data.every((r) => r.source === "APPLE_HEALTH")).toBe(true);
expect(auditLog).toHaveBeenCalledWith(
"nutrient.batch.ingest",
expect.objectContaining({
details: expect.objectContaining({ source: "APPLE_HEALTH" }),
}),
);
});
});
+1
View File
@@ -511,6 +511,7 @@ export const USER_RESET = {
documentsLayoutJson: Prisma.DbNull,
moduleListLayoutJson: Prisma.DbNull,
activityGoalsJson: Prisma.DbNull,
nutrientTargetsJson: Prisma.DbNull,
reportSelectionJson: Prisma.DbNull,
modulePreferencesJson: Prisma.DbNull,
healthScoreConfigJson: Prisma.DbNull,
@@ -71,6 +71,7 @@ export const accountSettingsBackupSchema = z
// because no codec reads it, so such a file restores everything else.
previewFeaturesJson: z.unknown().optional(),
activityGoalsJson: z.unknown().optional(),
nutrientTargetsJson: z.unknown().optional(),
reportSelectionJson: z.unknown().optional(),
globalExcludedInjectionSites: z.array(z.string()).optional(),
healthKitConfigJson: z.unknown().optional(),
+36
View File
@@ -62,6 +62,8 @@ import { UNREADABLE_EXPORT_MARKER } from "@/lib/export/unreadable-marker";
import { locales } from "@/lib/i18n/config";
import { thresholdsUpdateSchema } from "@/lib/validations/thresholds";
import { activityGoalsSchema } from "@/lib/validations/activity-goals";
import { isNutrientCode } from "@/lib/nutrients/catalog";
import { parseNutrientTarget } from "@/lib/validations/nutrient-targets";
import { isPublicUrl } from "@/lib/validations/notifications";
import {
glucoseUnitPatchSchema,
@@ -291,6 +293,39 @@ const activityGoals: SettingCodec = {
},
};
/**
* The daily nutrient targets, code by code. A target outside its code's range,
* or a code this release does not know, is dropped and named; the valid
* targets beside it still come back.
*/
const nutrientTargets: SettingCodec = {
write: (row) => ({ nutrientTargetsJson: row.nutrientTargetsJson ?? null }),
read: (entry) => {
if (!has(entry, "nutrientTargetsJson")) return undefined;
const value = entry.nutrientTargetsJson;
if (value === null) return Prisma.DbNull;
if (typeof value !== "object" || Array.isArray(value)) {
return new Refused("nutrientTargetsJson");
}
const kept: Record<string, { value: number; direction: string }> = {};
const refused: string[] = [];
for (const [code, raw] of Object.entries(value)) {
const target = isNutrientCode(code)
? parseNutrientTarget(code, raw)
: null;
if (target) {
kept[code] = { value: target.value, direction: target.direction };
} else {
refused.push(`nutrientTargetsJson.${code}`);
}
}
return new PartlyRefused(
Object.keys(kept).length === 0 ? Prisma.DbNull : kept,
refused,
);
},
};
const injectionSites = Object.values(InjectionSite) as string[];
/** The injection sites to avoid everywhere; an unknown site is dropped. */
@@ -540,6 +575,7 @@ const ACCOUNT_SETTING_CODECS = {
documentsLayoutJson: json("documentsLayoutJson"),
moduleListLayoutJson: json("moduleListLayoutJson"),
activityGoalsJson: activityGoals,
nutrientTargetsJson: nutrientTargets,
reportSelectionJson: json("reportSelectionJson"),
globalExcludedInjectionSites: excludedSites,
healthKitConfigJson: json("healthKitConfigJson"),
+56
View File
@@ -23,12 +23,17 @@ import {
nutrientWaterWriteSchema,
nutrientWaterWriteResponseSchema,
} from "@/lib/validations/nutrients";
import {
nutrientTargetsPatchSchema,
nutrientTargetsResponseSchema,
} from "@/lib/validations/nutrient-targets";
import {
dataEnvelope,
errorEnvelope,
idempotencyKeyParameter,
idempotentWrite,
recordRefusal,
recordWriteRateLimitResponse,
stdResponses,
} from "./shared";
@@ -216,4 +221,55 @@ export const nutrientPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/nutrients/targets": {
get: {
tags: ["Nutrients"],
summary: "Daily nutrient targets",
description:
"The daily targets the person set for themselves, keyed by catalog code, each `{ value, direction }` in the code's canonical unit: `target` is an amount to reach, `limit` one to stay under. Only codes with a target appear; there is no default. Owner only. `GET /api/nutrients/daily` carries the one for its code as `personalTarget`. Behind the opt-in `nutrients` module.",
responses: {
"200": {
description: "The targets.",
content: {
"application/json": {
schema: dataEnvelope(
nutrientTargetsResponseSchema,
"NutrientTargetsEnvelope",
),
},
},
},
...moduleDisabled,
...stdResponses,
},
},
patch: {
tags: ["Nutrients"],
summary: "Set daily nutrient targets",
description:
"Sets the targets the body names and keeps the rest; `null` clears one. An unknown code, or a value at or below 0 or above the code's plausibility cap, is refused with the multi-issue 422. Owner only: a shared or delegated session cannot change another person's targets. Behind the opt-in `nutrients` module.",
requestBody: {
required: true,
content: {
"application/json": { schema: nutrientTargetsPatchSchema },
},
},
responses: {
"200": {
description: "The targets after the change.",
content: {
"application/json": {
schema: dataEnvelope(
nutrientTargetsResponseSchema,
"NutrientTargetsPatchEnvelope",
),
},
},
},
...moduleDisabled,
...stdResponses,
...recordWriteRateLimitResponse,
},
},
},
};
@@ -0,0 +1,67 @@
import { describe, expect, it } from "vitest";
import {
mergeNutrientTargets,
nutrientTargetCodes,
nutrientTargetsPatchSchema,
parseNutrientTargets,
} from "../nutrient-targets";
describe("nutrient targets", () => {
it("accepts a target or a limit per catalog code and null to clear", () => {
const parsed = nutrientTargetsPatchSchema.safeParse({
targets: {
protein: { value: 120, direction: "target" },
sugar: { value: 40, direction: "limit" },
energy: null,
},
});
expect(parsed.success).toBe(true);
});
it("refuses an unknown code, a value at or below zero, and one above the code's cap", () => {
for (const targets of [
{ creatine: { value: 5, direction: "target" } },
{ protein: { value: 0, direction: "target" } },
{ protein: { value: 1001, direction: "target" } },
{ energy: { value: 2000, direction: "maximum" } },
{ energy: { value: 2000, direction: "target", extra: 1 } },
]) {
expect(
nutrientTargetsPatchSchema.safeParse({ targets }).success,
JSON.stringify(targets),
).toBe(false);
}
});
it("merges code by code: named codes change, null clears, the rest stay", () => {
const current = parseNutrientTargets({
protein: { value: 100, direction: "target" },
sugar: { value: 50, direction: "limit" },
});
const next = mergeNutrientTargets(current, {
targets: {
protein: { value: 120, direction: "target" },
sugar: null,
fiber: { value: 30, direction: "target" },
},
});
expect(next).toEqual({
protein: { value: 120, direction: "target" },
fiber: { value: 30, direction: "target" },
});
expect(nutrientTargetCodes(next)).toEqual(["protein", "fiber"]);
});
it("reads a damaged stored value code by code and never throws", () => {
expect(parseNutrientTargets(null)).toEqual({});
expect(parseNutrientTargets([1, 2])).toEqual({});
expect(
parseNutrientTargets({
protein: { value: 120, direction: "target" },
sugar: { value: -1, direction: "limit" },
retired_code: { value: 1, direction: "target" },
}),
).toEqual({ protein: { value: 120, direction: "target" } });
});
});
@@ -124,6 +124,16 @@
"stepsPerMonth": 250000,
"workoutsPerWeek": 4
},
"nutrientTargetsJson": {
"sugar": {
"value": 40,
"direction": "limit"
},
"protein": {
"value": 120,
"direction": "target"
}
},
"reportSelectionJson": {
"roundTrip": "rt-User-reportSelectionJson"
},
@@ -2571,6 +2581,16 @@
"stepsPerMonth": 250000,
"workoutsPerWeek": 4
},
"nutrientTargetsJson": {
"sugar": {
"value": 40,
"direction": "limit"
},
"protein": {
"value": 120,
"direction": "target"
}
},
"reportSelectionJson": {
"roundTrip": "rt-User-reportSelectionJson"
},
@@ -67,6 +67,16 @@
"stepsPerMonth": 250000,
"workoutsPerWeek": 4
},
"nutrientTargetsJson": {
"sugar": {
"value": 40,
"direction": "limit"
},
"protein": {
"value": 120,
"direction": "target"
}
},
"reportSelectionJson": {
"roundTrip": "rt-User-reportSelectionJson"
},
@@ -1737,6 +1747,16 @@
"stepsPerMonth": 250000,
"workoutsPerWeek": 4
},
"nutrientTargetsJson": {
"sugar": {
"value": 40,
"direction": "limit"
},
"protein": {
"value": 120,
"direction": "target"
}
},
"reportSelectionJson": {
"roundTrip": "rt-User-reportSelectionJson"
},
@@ -335,7 +335,7 @@
"symptomDefinitions": 2,
"lifeEvents": 3
},
"accountSettingsApplied": 61,
"accountSettingsApplied": 62,
"skipped": {
"catalogueKeys": [],
"links": 0
@@ -335,7 +335,7 @@
"symptomDefinitions": 0,
"lifeEvents": 0
},
"accountSettingsApplied": 61,
"accountSettingsApplied": 62,
"skipped": {
"catalogueKeys": [],
"links": 0
@@ -2787,6 +2787,16 @@
"stepsPerMonth": 250000,
"workoutsPerWeek": 4
},
"nutrientTargetsJson": {
"sugar": {
"value": 40,
"direction": "limit"
},
"protein": {
"value": 120,
"direction": "target"
}
},
"glucoseUnit": "mmol/L",
"hasDiabetes": true,
"labsLocalOcrEnabled": true,
@@ -3046,6 +3056,16 @@
"stepsPerMonth": 250000,
"workoutsPerWeek": 4
},
"nutrientTargetsJson": {
"sugar": {
"value": 40,
"direction": "limit"
},
"protein": {
"value": 120,
"direction": "target"
}
},
"reportSelectionJson": {
"roundTrip": "rt-User-reportSelectionJson"
},
@@ -381,7 +381,7 @@
"symptomDefinitions": 0,
"lifeEvents": 0
},
"accountSettingsApplied": 61,
"accountSettingsApplied": 62,
"skipped": {
"catalogueKeys": [
{
@@ -2281,6 +2281,16 @@
"stepsPerMonth": 250000,
"workoutsPerWeek": 4
},
"nutrientTargetsJson": {
"sugar": {
"value": 40,
"direction": "limit"
},
"protein": {
"value": 120,
"direction": "target"
}
},
"glucoseUnit": "mmol/L",
"hasDiabetes": true,
"labsLocalOcrEnabled": true,
@@ -2483,6 +2493,16 @@
"stepsPerMonth": 250000,
"workoutsPerWeek": 4
},
"nutrientTargetsJson": {
"sugar": {
"value": 40,
"direction": "limit"
},
"protein": {
"value": 120,
"direction": "target"
}
},
"reportSelectionJson": {
"roundTrip": "rt-User-reportSelectionJson"
},
@@ -909,6 +909,7 @@
"moodTagLayoutJson": null,
"moduleListLayoutJson": null,
"activityGoalsJson": null,
"nutrientTargetsJson": null,
"glucoseUnit": null,
"hasDiabetes": false,
"labsLocalOcrEnabled": false,
@@ -1043,6 +1043,7 @@
"moodTagLayoutJson": null,
"moduleListLayoutJson": null,
"activityGoalsJson": null,
"nutrientTargetsJson": null,
"glucoseUnit": null,
"hasDiabetes": false,
"labsLocalOcrEnabled": false,
@@ -1254,6 +1255,7 @@
"documentsLayoutJson": null,
"moduleListLayoutJson": null,
"activityGoalsJson": null,
"nutrientTargetsJson": null,
"reportSelectionJson": null,
"globalExcludedInjectionSites": [],
"healthKitConfigJson": null,
@@ -2402,6 +2402,16 @@
"stepsPerMonth": 250000,
"workoutsPerWeek": 4
},
"nutrientTargetsJson": {
"sugar": {
"value": 40,
"direction": "limit"
},
"protein": {
"value": 120,
"direction": "target"
}
},
"glucoseUnit": "mmol/L",
"hasDiabetes": true,
"labsLocalOcrEnabled": true,
+5
View File
@@ -1571,6 +1571,11 @@ export const USER_FILL_OVERRIDES: Readonly<Record<string, unknown>> = {
// The restore admits goal by goal against the goals schema, so the generic
// `{ roundTrip }` blob would be refused as an unknown key, not carried.
"User.activityGoalsJson": { workoutsPerWeek: 4, stepsPerMonth: 250_000 },
// Admitted code by code against the target schema, like the goals above.
"User.nutrientTargetsJson": {
protein: { value: 120, direction: "target" },
sugar: { value: 40, direction: "limit" },
},
"User.globalExcludedInjectionSites": ["THIGH_LEFT"],
"User.avatarBytes": () => {
const bytes = new Uint8Array(new ArrayBuffer(AVATAR_PNG.byteLength));
@@ -0,0 +1,130 @@
/**
* `GET` / `PATCH /api/nutrients/targets` and the target the daily series
* carries, against the real database and through the real API kit (#1402).
*/
import { beforeEach, describe, expect, it } from "vitest";
import type { User } from "@/generated/prisma/client";
import { GET, PATCH } from "@/app/api/nutrients/targets/route";
import { GET as GET_DAILY } from "@/app/api/nutrients/daily/route";
import { MEASUREMENTS_WRITE_SCOPE } from "@/lib/measurements/scopes";
import { callRoute, type RouteAuth } from "../../kit/call-route";
import { makeSession, makeToken, makeUser } from "../../kit/factories";
import { getPrismaClient, truncateAllTables } from "../setup";
const prisma = getPrismaClient();
const ROUTE = "/api/nutrients/targets";
type Targets = Record<string, { value: number; direction: string }>;
beforeEach(() => truncateAllTables(prisma));
function nutrientUser(): Promise<User> {
return makeUser({ modulePreferencesJson: { nutrients: true } });
}
function patch(targets: Record<string, unknown>, auth: RouteAuth) {
return callRoute<{ targets: Targets }>(PATCH, {
method: "PATCH",
route: ROUTE,
body: { targets },
auth,
});
}
async function stored(user: Pick<User, "id">) {
const row = await prisma.user.findUnique({
where: { id: user.id },
select: { nutrientTargetsJson: true },
});
return row?.nutrientTargetsJson ?? null;
}
describe("/api/nutrients/targets", () => {
it("sets, merges and clears targets code by code", async () => {
const user = await nutrientUser();
const session = await makeSession(user);
const first = await patch(
{
protein: { value: 120, direction: "target" },
sugar: { value: 40, direction: "limit" },
},
session,
);
expect(first.status).toBe(200);
const second = await patch(
{ sugar: null, energy: { value: 2200, direction: "target" } },
session,
);
expect(second.data.targets).toEqual({
energy: { value: 2200, direction: "target" },
protein: { value: 120, direction: "target" },
});
expect(await stored(user)).toEqual(second.data.targets);
const read = await callRoute<{ targets: Targets }>(GET, {
method: "GET",
route: ROUTE,
auth: session,
});
expect(read.data.targets).toEqual(second.data.targets);
await patch({ energy: null, protein: null }, session);
expect(await stored(user)).toBeNull();
});
it("refuses an unknown code or an out-of-range value with 422 and stores nothing", async () => {
const user = await nutrientUser();
const session = await makeSession(user);
for (const targets of [
{ creatine: { value: 5, direction: "target" } },
{ protein: { value: 5000, direction: "target" } },
]) {
const res = await patch(targets, session);
expect(res.status, JSON.stringify(targets)).toBe(422);
}
expect(await stored(user)).toBeNull();
});
it("refuses with module.disabled while the module is off", async () => {
const user = await makeUser();
const res = await patch(
{ protein: { value: 120, direction: "target" } },
await makeSession(user),
);
expect(res.status).toBe(403);
expect(res.meta?.errorCode).toBe("module.disabled");
});
it("refuses a measurements:write token: a bridge cannot set targets", async () => {
const user = await nutrientUser();
const res = await patch(
{ protein: { value: 120, direction: "target" } },
await makeToken(user, { permissions: [MEASUREMENTS_WRITE_SCOPE] }),
);
expect(res.status).toBe(403);
expect(await stored(user)).toBeNull();
});
it("returns the code's target on the daily series, and null for a code without one", async () => {
const user = await nutrientUser();
const session = await makeSession(user);
await patch({ protein: { value: 120, direction: "target" } }, session);
const daily = (nutrient: string) =>
callRoute<{ personalTarget: unknown }>(GET_DAILY, {
method: "GET",
route: "/api/nutrients/daily",
query: { nutrient, days: 7 },
auth: session,
});
expect((await daily("protein")).data.personalTarget).toEqual({
value: 120,
direction: "target",
});
expect((await daily("water")).data.personalTarget).toBeNull();
});
});
+29 -1
View File
@@ -33,6 +33,7 @@ import {
import { GET as getMe } from "@/app/api/auth/me/route";
import * as profile from "@/app/api/user/profile/route";
import * as nutrientTargets from "@/app/api/nutrients/targets/route";
import * as diabetes from "@/app/api/auth/me/diabetes/route";
import * as autoAiRead from "@/app/api/auth/me/documents-auto-ai-read/route";
import * as labsOcr from "@/app/api/auth/me/labs-local-ocr/route";
@@ -449,12 +450,39 @@ function entries(user: Pick<User, "id">): Entry[] {
handler: modules.PATCH,
method: "PATCH",
route: "/api/auth/me/modules",
body: { mood: false },
// Nutrients on as well: the nutrient-target entry below is behind it.
body: { mood: false, nutrients: true },
},
read: get(modules.GET, "/api/auth/me/modules", "modules.mood"),
expected: false,
me: { pick: (me) => at(me, "modules.mood"), expected: false },
},
{
columns: ["nutrientTargetsJson"],
write: {
handler: nutrientTargets.PATCH,
method: "PATCH",
route: "/api/nutrients/targets",
body: {
targets: {
protein: { value: 120, direction: "target" },
sugar: { value: 40, direction: "limit" },
},
},
},
read: {
call: {
handler: nutrientTargets.GET,
method: "GET",
route: "/api/nutrients/targets",
},
pick: (res) => [
at(res.data, "targets.protein.value"),
at(res.data, "targets.sugar.direction"),
],
},
expected: [120, "limit"],
},
{
columns: ["healthScoreConfigJson"],
write: {