feat(medications,coach,insights): record the dose you actually took

An intake can carry the dose that was actually taken — editable in the
quick-add and log dialogs, shown as a quiet deviation line in the
history. The measurements and mood lists refresh by pull on touch, the
insight sub-pages gain the same customize entry as the overview, and an
answered coach follow-up offers to adopt the answer into the matching
self-context field.
This commit is contained in:
Marc-André Bombeck committed 2026-06-11 00:10:01 +02:00
1 parent ce3b4c70c8
commit 7e7e17c68c
29 files changed
+886 -744

No files matched your search

+181
View File
@@ -0,0 +1,181 @@
/**
* POST /api/coach/about-me/adopt — fold a clarifying-question answer
* back into the stored self-context.
*
* v1.16.4 — closes the questions loop: the Coach composer's pending
* chips (`/api/coach/about-me/questions`) insert a question the user
* answers in their own words; this endpoint lets that answer flow back
* into the matching structured self-context field instead of living
* only in the chat transcript. Additive — the existing GET/PUT
* `/api/coach/about-me` contract is untouched.
*
* Semantics:
* - The target field is picked from the QUESTION wording (allergy /
* condition keywords across the six UI locales; everything else
* lands on `coachFocus`, the "what the Coach should know" slot).
* - Dedupe: an answer already contained in the target field (or in
* the free-text `aboutMe`) is a no-op (`adopted: false`) — tapping
* the offer twice or re-answering the same chip cannot stack
* duplicate prose.
* - Append, never replace: existing text stays; the answer joins on
* its own line, encrypted at rest like every self-context write.
* A structured field at its cap overflows into `aboutMe`.
* - Audit rows carry lengths only — the text is free-form health
* prose and must not land in plaintext audit details.
*/
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
getClientIp,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { prisma } from "@/lib/db";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { encryptToBytes } from "@/lib/ai/coach/bytes-codec";
import { getSelfContextForUser } from "@/lib/ai/coach/about-me";
import {
ABOUT_ME_FIELD_MAX_CHARS,
ABOUT_ME_MAX_CHARS,
aboutMeAdoptSchema,
} from "@/lib/validations/about-me";
const POST_RATE_LIMIT = 30;
const POST_WINDOW_MS = 60_000;
type StructuredField = "conditions" | "allergies" | "coachFocus";
/**
* Keyword match against the question wording, covering the six UI
* locales the question generator writes in (de / en / es / fr / it /
* pl). Stems, not words, so inflections match. Anything that is not
* clearly an allergy or condition question lands on `coachFocus` — the
* generic "worth knowing for the Coach" slot.
*/
function matchSelfContextField(question: string): StructuredField {
const q = question.toLowerCase();
const allergyStems = [
"allerg", // de/en/fr/it
"alergi", // es/pl
"uczulen", // pl
"intoleran", // de/en/es/it
"unverträglich", // de
];
if (allergyStems.some((s) => q.includes(s))) return "allergies";
const conditionStems = [
"erkrank", // de
"krankheit", // de
"diagnos", // de/en/es/fr/it/pl
"condition", // en
"chronic", // en
"chronisch", // de
"enfermedad", // es
"maladie", // fr
"malatt", // it
"chorob", // pl
];
if (conditionStems.some((s) => q.includes(s))) return "conditions";
return "coachFocus";
}
/** Whitespace-collapsed lowercase form for containment dedupe. */
function normalise(s: string): string {
return s.toLowerCase().replace(/\s+/g, " ").trim();
}
export const POST = apiHandler(async (req: Request) => {
const { user } = await requireAuth();
const rl = await checkRateLimit(
`coach-about-me:adopt:${user.id}`,
POST_RATE_LIMIT,
POST_WINDOW_MS,
);
if (!rl.allowed) {
const response = apiError("Too many requests", 429);
for (const [k, v] of Object.entries(rateLimitHeaders(rl))) {
response.headers.set(k, v);
}
return response;
}
const { data: body, error: jsonError } = await safeJson(req, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = aboutMeAdoptSchema.safeParse(body);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422);
}
const { question, answer } = parsed.data;
const ctx = await getSelfContextForUser(user.id);
let field: StructuredField | "aboutMe" = matchSelfContextField(question);
const normAnswer = normalise(answer);
// Dedupe BEFORE any write: an answer already present in the target
// field or in the free-text aboutMe never stacks a second copy.
const targetExisting = ctx[field];
if (
(targetExisting && normalise(targetExisting).includes(normAnswer)) ||
(ctx.aboutMe && normalise(ctx.aboutMe).includes(normAnswer))
) {
annotate({
action: { name: "coach.about_me.adopt_deduped" },
meta: { field },
});
return apiSuccess({ adopted: false, field, reason: "duplicate" });
}
// Append on its own line; a structured field at its cap overflows
// into the free-text aboutMe (4000 chars) rather than failing the
// adoption outright.
let nextValue = targetExisting ? `${targetExisting}\n${answer}` : answer;
if (nextValue.length > ABOUT_ME_FIELD_MAX_CHARS) {
field = "aboutMe";
nextValue = ctx.aboutMe ? `${ctx.aboutMe}\n${answer}` : answer;
if (nextValue.length > ABOUT_ME_MAX_CHARS) {
return apiError("Self-context is full", 422);
}
}
// Field-by-field assembly (no mass assignment): exactly one encrypted
// column is written per adoption.
const column = (
{
conditions: "conditionsEncrypted",
allergies: "allergiesEncrypted",
coachFocus: "coachFocusEncrypted",
aboutMe: "aboutMeEncrypted",
} as const
)[field];
const payload = { [column]: encryptToBytes(nextValue) };
await prisma.userHealthProfile.upsert({
where: { userId: user.id },
create: { userId: user.id, ...payload },
update: payload,
select: { updatedAt: true },
});
await auditLog("coach.about_me.adopted", {
userId: user.id,
ipAddress: getClientIp(req),
details: { field, answerLength: answer.length },
});
annotate({
action: { name: "coach.about_me.adopted" },
meta: { field, answer_length: answer.length },
});
return apiSuccess({ adopted: true, field });
});
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
@@ -89,6 +89,8 @@ interface SerializedDoseHistoryRow {
takenAt: string | null;
skipped: boolean;
autoMissed: boolean;
/** v1.16.4 — per-intake dose override; null = configured dose. */
doseTaken: string | null;
} | null;
}
@@ -161,6 +163,8 @@ export const GET = apiHandler(
autoMissed: true,
// v1.15.20 — USER_PIN rows bind by anchor in the read ledger.
attributionSource: true,
// v1.16.4 — per-intake dose override for the ledger's deviation hint.
doseTaken: true,
},
});
@@ -171,6 +175,7 @@ export const GET = apiHandler(
skipped: e.skipped,
autoMissed: e.autoMissed,
pinned: e.attributionSource === "USER_PIN",
doseTaken: e.doseTaken,
}));
const lastIntakeAt = lastNonSkippedTakenAt(mapped);
@@ -242,6 +247,7 @@ export const GET = apiHandler(
skipped: e.skipped,
autoMissed: e.autoMissed,
pinned: e.pinned,
doseTaken: e.doseTaken,
}));
const rows = reconstructDoseHistory(bands, historyIntakes, now);
@@ -266,6 +272,7 @@ export const GET = apiHandler(
takenAt: row.intake.takenAt?.toISOString() ?? null,
skipped: row.intake.skipped,
autoMissed: row.intake.autoMissed ?? false,
doseTaken: row.intake.doseTaken ?? null,
}
: null,
}));
@@ -91,8 +91,14 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
idempotencyKey,
injectionSite,
forceSlotInstant,
doseTaken,
} = parsed.data;
// v1.16.4 — the dose override documents a consumed dose, so it only
// applies to a taken (non-skipped) write; on a skip it is silently
// dropped (the slot consumed nothing).
const resolvedDoseTaken = !skipped && doseTaken ? doseTaken : null;
// v1.8.5 — resolve + server-validate the optional injection site. Load
// the medication's delivery form + tracking opt-in + per-medication
// allowed sites, plus the user's global exclusion deny-list. A site
@@ -295,6 +301,9 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
// injection taken write supplied an allowed site).
injectionSite: resolvedInjectionSite,
attributionSource,
// v1.16.4 — per-intake dose override (null unless a taken write
// carried one).
doseTaken: resolvedDoseTaken,
});
event = applied.row;
consumedTransition = applied.consumedTransition;
@@ -342,6 +351,7 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
createSource: "WEB",
injectionSite: resolvedInjectionSite,
attributionSource,
doseTaken: resolvedDoseTaken,
});
event = applied.row;
consumedTransition = applied.consumedTransition;
@@ -371,6 +381,10 @@ async function postIntake(request: NextRequest, { params }: RouteParams) {
...(resolvedInjectionSite !== null && {
injectionSite: resolvedInjectionSite,
}),
// v1.16.4 — dose override only on a taken write carrying one.
...(resolvedDoseTaken !== null && {
doseTaken: resolvedDoseTaken,
}),
},
}),
// Reset snooze when medication is taken
@@ -96,6 +96,11 @@ const bulkEntrySchema = z.object({
.datetime({ offset: true })
.transform((s) => new Date(s))
.optional(),
// v1.16.4 — per-entry dose override, mirroring the single intake
// route: free text (max 50 chars, like `Medication.dose`), persisted
// only on a taken entry. Absent = the configured medication dose
// applies.
doseTaken: z.string().trim().min(1).max(50).optional(),
});
const bulkPayloadSchema = z.object({
@@ -381,6 +386,8 @@ async function postBulk(request: NextRequest): Promise<Response> {
createSource: "API",
injectionSite: resolvedInjectionSite,
attributionSource,
// v1.16.4 — dose override only documents a consumed dose.
doseTaken: (!entry.skipped && entry.doseTaken) || null,
});
if (applied.noDowngradeNoOp) {
// C2 — pending echo onto an already-actioned slot. Report it as a
@@ -451,6 +458,7 @@ async function postBulk(request: NextRequest): Promise<Response> {
createSource: "API",
injectionSite: resolvedInjectionSite,
attributionSource,
doseTaken: (!entry.skipped && entry.doseTaken) || null,
});
if (applied.noDowngradeNoOp) {
duplicates += 1;
@@ -485,6 +493,9 @@ async function postBulk(request: NextRequest): Promise<Response> {
...(resolvedInjectionSite !== null && {
injectionSite: resolvedInjectionSite,
}),
// v1.16.4 — dose override only on a taken entry carrying one.
...(!entry.skipped &&
entry.doseTaken && { doseTaken: entry.doseTaken }),
},
});
inserted += 1;