feat(symptoms): add person-defined symptoms and timestamped occurrences

A symptom of one's own ("aura", "headache") is a definition with an
encrypted name and an icon from the cycle custom-symptom allowlist; each
occurrence carries a time, a 0-10 intensity (the pain score's scale), an
optional encrypted note and an optional link to one of the record's open
illness episodes. Both ride the illness module: every route answers
illness.disabled when it is off.

- Migration 0369 (idempotent): symptom_definitions and symptom_events,
  intensity CHECK 0-10, episode link ON DELETE SET NULL.
- /api/symptoms/definitions{,/[id]} and /api/symptoms/events{,/[id]}:
  eight active definitions per record (a hidden one frees its slot,
  showing it again re-checks), hide or purge, events create/list/edit/
  delete, a new link must name an open episode of the same record
  (422 symptoms.episode.notOpen). Error group symptoms.*.
- Sharing: reads at READ, logging an occurrence at WRITE, defining and
  editing at MANAGE; C1/C3/C4 audit details; frozen lists, the handler
  matrix and the activity verbs updated.
- Both encrypted columns registered and rotated; both models in the wipe
  plan; both carried at both backup ends with occurrences nested in their
  definition, plaintext in a portable file and ciphertext in a recovery
  file, and a link to an episode the file lacks dropped and named
  (symptomEpisodeReference).
- OpenAPI regenerated.
This commit is contained in:
Marc-André Bombeck committed 2026-10-03 21:13:45 +02:00
1 parent 7cd323499e
commit d6571c4e9c
30 files changed
+3091 -16

No files matched your search

+192
View File
@@ -0,0 +1,192 @@
/**
* One occurrence of a person-defined symptom (v1.40).
*
* PATCH /api/symptoms/events/{id} — change the time, intensity, note or
* episode link. A new link must name an open episode of the record;
* an unchanged link to an episode that has since resolved is kept.
* DELETE /api/symptoms/events/{id} — remove it.
*
* Owner-scoped (another account's id is a 404), module-gated on the record,
* MANAGE on a shared record. The note is never logged.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import {
apiSuccess,
apiError,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import {
destroyedDetails,
overwriteDetails,
} from "@/lib/sharing/audit-details";
import { invalidateUserHealthContext } from "@/lib/cache/invalidate";
import { requireIllnessEnabled } from "@/lib/illness/gate";
import {
encryptSymptomText,
isLinkableEpisode,
symptomEventUpdateSchema,
toSymptomEventDTO,
} from "@/lib/symptoms/server";
export const dynamic = "force-dynamic";
type RouteParams = { params: Promise<{ id: string }> };
function notFound(): Response {
return apiError("Symptom event not found", 404, {
errorCode: "symptoms.event.notFound",
});
}
export const PATCH = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("manage", "illness");
const gate = await requireIllnessEnabled(user.id);
if (!gate.enabled) return gate.response;
const { id } = await params;
const { data: rawBody, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = symptomEventUpdateSchema.safeParse(rawBody);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "symptoms.invalid",
});
}
const entry = parsed.data;
const existing = await prisma.symptomEvent.findFirst({
where: { id, userId: user.id },
select: {
id: true,
occurredAt: true,
intensity: true,
episodeId: true,
},
});
if (!existing) return notFound();
if (
entry.episodeId &&
entry.episodeId !== existing.episodeId &&
!(await isLinkableEpisode(user.id, entry.episodeId))
) {
return apiError("Episode is not open", 422, {
errorCode: "symptoms.episode.notOpen",
});
}
const updated = await prisma.symptomEvent.update({
where: { id: existing.id },
data: {
...(entry.occurredAt !== undefined
? { occurredAt: entry.occurredAt }
: {}),
...(entry.intensity !== undefined
? { intensity: entry.intensity }
: {}),
...(entry.note !== undefined
? {
noteEncrypted: entry.note ? encryptSymptomText(entry.note) : null,
}
: {}),
...(entry.episodeId !== undefined
? { episodeId: entry.episodeId ?? null }
: {}),
},
});
await auditLog("symptoms.event.update", {
userId: user.id,
ipAddress: getClientIp(request),
details: {
eventId: id,
...overwriteDetails({
before: {
occurredAt: existing.occurredAt,
intensity: existing.intensity,
episodeId: existing.episodeId,
},
after: {
occurredAt: updated.occurredAt,
intensity: updated.intensity,
episodeId: updated.episodeId,
},
redacted: entry.note !== undefined ? ["note"] : [],
}),
},
});
invalidateUserHealthContext(user.id);
annotate({
action: {
name: "symptoms.event.update",
entity_type: "symptom_event",
entity_id: id,
},
});
return apiSuccess(toSymptomEventDTO(updated));
},
);
export const DELETE = apiHandler(
async (request: NextRequest, { params }: RouteParams) => {
const { user } = await requireRecordAuth("manage", "illness");
const gate = await requireIllnessEnabled(user.id);
if (!gate.enabled) return gate.response;
const { id } = await params;
const existing = await prisma.symptomEvent.findFirst({
where: { id, userId: user.id },
select: {
id: true,
definitionId: true,
occurredAt: true,
intensity: true,
},
});
if (!existing) return notFound();
await prisma.symptomEvent.delete({ where: { id: existing.id } });
await auditLog("symptoms.event.delete", {
userId: user.id,
ipAddress: getClientIp(request),
// C3: the row is gone after this; the audit row says what it was. The
// symptom's name is the person's own words and stays out of it, so the
// label is the definition id.
details: destroyedDetails({
model: "SymptomEvent",
id,
label: existing.definitionId,
effectiveAt: existing.occurredAt,
extra: { intensity: existing.intensity },
}),
});
invalidateUserHealthContext(user.id);
annotate({
action: {
name: "symptoms.event.delete",
entity_type: "symptom_event",
entity_id: id,
},
});
return apiSuccess({ deleted: true });
},
);
+166
View File
@@ -0,0 +1,166 @@
/**
* Occurrences of person-defined symptoms (v1.40).
*
* GET /api/symptoms/events — newest first, optionally narrowed by
* `from` / `to` (ISO instants), `definitionId` and `episodeId`; at most
* 500 per page.
* POST /api/symptoms/events — log one (`{ definitionId, intensity,
* occurredAt?, note?, episodeId? }`). `occurredAt` defaults to now and
* may not lie in the future beyond the shared five-minute skew;
* `episodeId` must name one of the record's own episodes that is still
* open. The note is encrypted at rest.
*
* Module-gated on the record (`illness.disabled`). `userId` comes from auth
* and is never a body field.
*/
import { NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import {
apiSuccess,
apiError,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { apiHandler, requireRecordAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { withIdempotency } from "@/lib/idempotency";
import { auditLog } from "@/lib/auth/audit";
import { invalidateUserHealthContext } from "@/lib/cache/invalidate";
import { requireIllnessEnabled } from "@/lib/illness/gate";
import type { Prisma } from "@/generated/prisma/client";
import {
encryptSymptomText,
isLinkableEpisode,
symptomEventCreateSchema,
symptomEventListQuerySchema,
toSymptomEventDTO,
} from "@/lib/symptoms/server";
export const dynamic = "force-dynamic";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireRecordAuth("read", "illness");
const gate = await requireIllnessEnabled(user.id);
if (!gate.enabled) return gate.response;
const sp = request.nextUrl.searchParams;
const parsed = symptomEventListQuerySchema.safeParse({
from: sp.get("from") ?? undefined,
to: sp.get("to") ?? undefined,
definitionId: sp.get("definitionId") ?? undefined,
episodeId: sp.get("episodeId") ?? undefined,
limit: sp.get("limit") ?? undefined,
});
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "symptoms.invalid",
});
}
const q = parsed.data;
const occurredAt: Prisma.DateTimeFilter = {};
if (q.from) occurredAt.gte = new Date(q.from);
if (q.to) occurredAt.lte = new Date(q.to);
const rows = await prisma.symptomEvent.findMany({
where: {
userId: user.id,
...(q.from || q.to ? { occurredAt } : {}),
...(q.definitionId ? { definitionId: q.definitionId } : {}),
...(q.episodeId ? { episodeId: q.episodeId } : {}),
},
orderBy: [{ occurredAt: "desc" }, { id: "desc" }],
take: q.limit,
});
annotate({
action: { name: "symptoms.event.list" },
meta: { count: rows.length, limit: q.limit },
});
return apiSuccess({
events: rows.map(toSymptomEventDTO),
limit: q.limit,
hasMore: rows.length === q.limit,
});
});
// A retry from a flaky connection re-sends the same `Idempotency-Key` and gets
// the first answer back instead of a second occurrence at the same minute.
export const POST = apiHandler(withIdempotency<[NextRequest]>(postEvent));
async function postEvent(request: NextRequest): Promise<Response> {
// WRITE, like opening an episode or adding a reading: logging what happened
// is an admitted delegated write; editing or removing it is MANAGE.
const { user } = await requireRecordAuth("write", "illness");
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 = symptomEventCreateSchema.safeParse(rawBody);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422, {
errorCode: "symptoms.invalid",
});
}
const entry = parsed.data;
// A hidden definition stays loggable from an older client's cached list;
// only another account's id (or none) is refused.
const definition = await prisma.symptomDefinition.findFirst({
where: { id: entry.definitionId, userId: user.id },
select: { id: true },
});
if (!definition) {
return apiError("Symptom not found", 404, {
errorCode: "symptoms.definition.notFound",
});
}
if (entry.episodeId && !(await isLinkableEpisode(user.id, entry.episodeId))) {
return apiError("Episode is not open", 422, {
errorCode: "symptoms.episode.notOpen",
});
}
const created = await prisma.symptomEvent.create({
data: {
userId: user.id,
definitionId: definition.id,
occurredAt: entry.occurredAt ?? new Date(),
intensity: entry.intensity,
noteEncrypted: entry.note ? encryptSymptomText(entry.note) : null,
episodeId: entry.episodeId ?? null,
},
});
await auditLog("symptoms.event.create", {
userId: user.id,
ipAddress: getClientIp(request),
details: {
eventId: created.id,
definitionId: created.definitionId,
linked: created.episodeId !== null,
},
});
invalidateUserHealthContext(user.id);
annotate({
action: {
name: "symptoms.event.create",
entity_type: "symptom_event",
entity_id: created.id,
},
meta: { linked: created.episodeId !== null },
});
return apiSuccess(toSymptomEventDTO(created), 201);
}