Files
HealthLog/src/app/api/illness/episodes/route.ts
T
Marc-André Bombeck b079431a8d feat(illness): add the condition-journal MVP behind a born-gated module
Introduce a retrospective illness/condition journal: episodes with a
lifecycle (acute / chronic-ongoing / recurring / flare) and a daily
symptom timeline forked structurally from the cycle log-day surface. The
journal is a record, not a medical device — no prediction or diagnosis UI.

- Register `illness` as a born-gated (opt-in / default-off) module. The
  gate resolver flips the disabled-allowlist default to off for born-gated
  keys, so the surface stays dark until the account opts in from the
  Modules hub. `isIllnessEnabled` + `requireIllnessEnabled` delegate to the
  module foundation (one source of truth) and re-stamp an illness errorCode.
- Episode CRUD under /api/illness: list / create / get / edit / resolve /
  delete, plus a per-episode-day day-log upsert on (episodeId, date). Every
  route wraps apiHandler, Zod-validates with returnAllZodIssues, narrows
  userId from auth, builds data field-by-field, and gates the module.
  Free-text notes encrypt at rest through the shared Bytes codec.
- Log-day sheet (cycle fork): ~8 Jackson/WURSS symptom chips 0-3 + a
  functional-impact group + fever + an encrypted note, one row per day.
- Episode history page + a born-gated nav entry, neutral palette, status
  via a neutral Badge, retrospective-only copy. i18n across all six locales.
- Cover the new routes in the module-route-gate inventory; unit tests for
  the day-log upsert, the gate enforcement, and the born-gated resolver.

The /api/auth/me module map now projects the `illness` flag (openapi.yaml
regenerated).
2026-06-16 21:09:35 +02:00

139 lines
4.4 KiB
TypeScript

/**
* `GET /api/illness/episodes` — newest-first list of the account's
* illness/condition episodes.
* `POST /api/illness/episodes` — create one episode.
*
* The illness journal is a CONDITION journal, retrospective-only — NEVER a
* predictor/diagnoser. Born-gated: a non-opted-in account (or an
* operator-disabled instance) 403s with `errorCode:"illness.disabled"`
* even with a valid Bearer token. `userId` is narrowed from auth and fed
* to the Prisma `where`; it is never a body field. The `data` object is
* built field-by-field (no mass assignment); `note` is encrypted at rest.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
apiSuccess,
apiError,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { requireIllnessEnabled } from "@/lib/illness/gate";
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import {
illnessEpisodeCreateSchema,
illnessEpisodeListQuerySchema,
} from "@/lib/validations/illness";
import { toIllnessEpisodeDTO } from "@/lib/illness/dto";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const gate = await requireIllnessEnabled(user.id);
if (!gate.enabled) return gate.response;
const params = new URL(request.url).searchParams;
const parsed = illnessEpisodeListQuerySchema.safeParse({
limit: params.get("limit") ?? undefined,
includeResolved: params.get("includeResolved") ?? undefined,
});
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "illness.episode.invalid",
});
}
const limit = parsed.data.limit ?? 50;
const rows = await prisma.illnessEpisode.findMany({
where: {
userId: user.id,
deletedAt: null,
...(parsed.data.includeResolved === "false" ? { resolvedAt: null } : {}),
},
orderBy: { onsetAt: "desc" },
take: limit,
});
annotate({
action: { name: "illness.episode.list", entity_type: "illness_episode" },
meta: { count: rows.length },
});
return apiSuccess(rows.map(toIllnessEpisodeDTO));
});
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
const gate = await requireIllnessEnabled(user.id);
if (!gate.enabled) return gate.response;
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = illnessEpisodeCreateSchema.safeParse(rawBody);
if (!parsed.success) {
annotate({
action: { name: "illness.episode.validation-failed" },
meta: { issue_count: parsed.error.issues.length },
});
return returnAllZodIssues(parsed.error, 422, {
errorCode: "illness.episode.invalid",
});
}
const entry = parsed.data;
// A FLARE/RECURRING bout may hang off a parent condition — verify the
// parent is owned + live before threading.
if (entry.parentConditionId) {
const parent = await prisma.illnessEpisode.findUnique({
where: { id: entry.parentConditionId },
select: { userId: true, deletedAt: true },
});
if (!parent || parent.userId !== user.id || parent.deletedAt !== null) {
return apiError("Parent condition not found", 404, {
errorCode: "illness.episode.parent-not-found",
});
}
}
// Field-by-field — never spread the parsed object whole.
const created = await prisma.illnessEpisode.create({
data: {
userId: user.id,
label: entry.label,
type: entry.type,
lifecycle: entry.lifecycle,
onsetAt: entry.onsetAt ? new Date(entry.onsetAt) : new Date(),
resolvedAt: entry.resolvedAt ? new Date(entry.resolvedAt) : null,
parentConditionId: entry.parentConditionId ?? null,
noteEncrypted: entry.note ? encryptToBytes(entry.note) : null,
},
});
await auditLog("illness.episode.create", {
userId: user.id,
ipAddress: getClientIp(request),
details: { episodeId: created.id, type: created.type },
});
annotate({
action: {
name: "illness.episode.create",
entity_type: "illness_episode",
entity_id: created.id,
},
meta: { type: created.type, lifecycle: created.lifecycle },
});
return apiSuccess(toIllnessEpisodeDTO(created), 201);
});