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

@@ -13,6 +13,7 @@ import { CoachInput } from "./coach-input";
import { HistoryRail } from "./history-rail";
import { MessageThread } from "./message-thread";
import { MobileRailTray } from "./mobile-rail-tray";
import { SelfContextAdoptOffer } from "./self-context-adopt-offer";
import { SelfContextChips } from "./self-context-chips";
import { SourcesRail } from "./sources-rail";
import { useResettableValue } from "./use-resettable-value";
@@ -113,6 +114,17 @@ export function CoachConversation({
const [historyTrayOpen, setHistoryTrayOpen] = useState(false);
const [sourcesTrayOpen, setSourcesTrayOpen] = useState(false);
const [inputValue, setInputValue] = useResettableValue(prefill ?? "");
// v1.16.4 — self-context backflow. `activeChipQuestion` remembers the
// clarifying-question chip the user tapped (the chip pre-fills the
// composer); when the next message answers it, `pendingAdopt` raises a
// quiet offer to fold the answer back into the Selbstauskunft.
const [activeChipQuestion, setActiveChipQuestion] = useState<string | null>(
null,
);
const [pendingAdopt, setPendingAdopt] = useState<{
question: string;
answer: string;
} | null>(null);
const { data: conversation } = useCoachConversation(currentConversationId);
const send = useSendCoachMessage({
@@ -137,16 +149,32 @@ export function CoachConversation({
async function handleSubmit(value: string) {
const trimmed = value.trim();
if (!trimmed || send.isStreaming) return;
// v1.16.4 — when this message answers a tapped clarifying-question
// chip, peel the inserted question off the front so only the user's
// own words form the adoptable answer. An empty remainder (the user
// deleted their answer or sent the bare question) raises no offer.
const chipQuestion = activeChipQuestion;
setActiveChipQuestion(null);
const answer = chipQuestion
? trimmed.startsWith(chipQuestion)
? trimmed.slice(chipQuestion.length).trim()
: trimmed
: null;
setInputValue("");
await send.send({
conversationId: currentConversationId ?? undefined,
message: trimmed,
});
if (chipQuestion && answer) {
setPendingAdopt({ question: chipQuestion, answer });
}
}
function handleNewChat() {
setCurrentConversationId(null);
setInputValue("");
setActiveChipQuestion(null);
setPendingAdopt(null);
send.reset();
}
@@ -239,9 +267,21 @@ export function CoachConversation({
chips. Tapping inserts the question into the composer
(the user answers it in their own words) and dismisses
the chip. Renders nothing when no questions pend. */}
{/* v1.16.4 — quiet adopt-into-self-context offer once a chip
question has been answered. Self-removes after settle. */}
{pendingAdopt && !send.isStreaming ? (
<SelfContextAdoptOffer
question={pendingAdopt.question}
answer={pendingAdopt.answer}
onDismiss={() => setPendingAdopt(null)}
/>
) : null}
<SelfContextChips
disabled={send.isStreaming}
onPick={(question) => setInputValue(`${question}\n`)}
onPick={(question) => {
setActiveChipQuestion(question);
setInputValue(`${question}\n`);
}}
/>
<CoachInput
value={inputValue}
@@ -0,0 +1,133 @@
"use client";
/**
* v1.16.4 — quiet "fold this answer back into your self-context" offer.
*
* When the user answers a pending clarifying-question chip (the chip
* inserted the question into the composer; the sent message is the
* answer), this strip appears above the composer and offers to adopt
* the answer into the matching Selbstauskunft field via
* `POST /api/coach/about-me/adopt`. One tap adopts (the server picks
* the field, dedupes, appends encrypted); the ✕ declines. After an
* adoption (or a server-side dedupe) a short confirmation lingers for a
* few seconds, then the strip removes itself — no modal, no toast, no
* vertical cost once settled.
*/
import { useEffect, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { BookmarkPlus, Check, Loader2, X } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
export interface SelfContextAdoptOfferProps {
/** The clarifying question the user just answered. */
question: string;
/** The composer message that answered it. */
answer: string;
/** Remove the strip (declined, or confirmation elapsed). */
onDismiss: () => void;
}
export function SelfContextAdoptOffer({
question,
answer,
onDismiss,
}: SelfContextAdoptOfferProps) {
const { t } = useTranslations();
const [settled, setSettled] = useState<"adopted" | "duplicate" | null>(null);
const adopt = useMutation({
mutationFn: async () => {
const res = await fetch("/api/coach/about-me/adopt", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ question, answer }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).data as { adopted: boolean };
},
onSuccess: (data) => {
setSettled(data.adopted ? "adopted" : "duplicate");
},
});
// Let the confirmation linger briefly, then fold the strip away.
useEffect(() => {
if (!settled) return;
const handle = window.setTimeout(onDismiss, 4000);
return () => window.clearTimeout(handle);
}, [settled, onDismiss]);
return (
<div
data-slot="coach-self-context-adopt"
className={cn(
"border-dracula-purple/30 bg-dracula-purple/10 mb-2 flex items-center gap-2 rounded-lg border px-3 py-2",
)}
>
{settled ? (
<p
role="status"
className="text-muted-foreground flex items-center gap-1.5 text-xs"
>
<Check
className="text-dracula-green size-3.5 shrink-0"
aria-hidden="true"
/>
{t(
settled === "adopted"
? "insights.coach.selfContextAdopt.done"
: "insights.coach.selfContextAdopt.duplicate",
)}
</p>
) : (
<>
<BookmarkPlus
className="text-dracula-purple size-3.5 shrink-0"
aria-hidden="true"
/>
<p className="text-muted-foreground min-w-0 flex-1 text-xs">
{t("insights.coach.selfContextAdopt.offer")}
</p>
<button
type="button"
data-slot="coach-self-context-adopt-confirm"
disabled={adopt.isPending}
onClick={() => adopt.mutate()}
className={cn(
"text-dracula-purple inline-flex min-h-8 shrink-0 items-center gap-1 rounded-full px-2.5 text-xs font-medium",
"hover:bg-dracula-purple/15 focus-visible:ring-dracula-purple/40 focus-visible:ring-2 focus-visible:outline-none",
"disabled:opacity-60",
)}
>
{adopt.isPending ? (
<Loader2
className="size-3 animate-spin motion-reduce:animate-none"
aria-hidden="true"
/>
) : null}
{t("insights.coach.selfContextAdopt.confirm")}
</button>
<button
type="button"
aria-label={t("insights.coach.selfContextAdopt.dismiss")}
data-slot="coach-self-context-adopt-dismiss"
onClick={onDismiss}
className={cn(
"text-muted-foreground hover:text-foreground flex min-h-8 items-center rounded-full px-1.5",
"hover:bg-dracula-purple/15 focus-visible:ring-dracula-purple/40 focus-visible:ring-2 focus-visible:outline-none",
)}
>
<X className="size-3" aria-hidden="true" />
</button>
</>
)}
{adopt.isError ? (
<p role="alert" className="text-destructive text-xs">
{t("insights.coach.selfContextAdopt.failed")}
</p>
) : null}
</div>
);
}
+27 -1
View File
@@ -3,7 +3,7 @@
import { useEffect, useRef, type ReactNode } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ListOrdered } from "lucide-react";
import { ListOrdered, Settings2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -227,6 +227,32 @@ export function SubPageShell({
<div className="flex shrink-0 items-center gap-0.5">
<TargetAdjustButton />
{coachLaunch ? <CoachLaunchButton variant="icon" /> : null}
{/* v1.16.4 — customise cog on every routed sub-page,
mirroring the mother page's tab-strip cog: same Settings2
glyph, same `/settings/insights` destination (overview
arrange + pill sort). Rightmost in the cluster so it sits
where the mother page's cog sits — far top-right — and
clearly apart from the self-gating target-adjust gear. */}
<Button
asChild
variant="ghost"
size="icon"
data-slot="insights-subpage-customize"
className={cn(
// Match the cluster's 40 px icon box + extended hit area
// (see `<TargetAdjustButton>` for the WCAG 2.5.5 note).
"text-muted-foreground hover:text-foreground relative size-10",
"before:absolute before:-inset-1.5 before:content-['']",
)}
>
<Link
href="/settings/insights"
aria-label={t("insights.customize")}
title={t("insights.customize")}
>
<Settings2 className="size-4" aria-hidden="true" />
</Link>
</Button>
</div>
</div>
{explainerMetric ? (
@@ -36,6 +36,8 @@ export interface LedgerRow {
takenAt: string | null;
skipped: boolean;
autoMissed: boolean;
/** v1.16.4 — per-intake dose override; null/absent = configured dose. */
doseTaken?: string | null;
} | null;
}
@@ -659,6 +659,19 @@ function LedgerRowItem({
})}
</p>
)}
{/* v1.16.4 — quiet per-intake dose override note. Only rows whose
take recorded a deviating dose carry one; the configured dose
stays implicit, so the ledger's rhythm is undisturbed. */}
{intake?.doseTaken && (
<p
className="text-muted-foreground text-xs"
data-slot="ledger-dose-taken"
>
{t("medications.detail.verlauf.doseTaken", {
dose: intake.doseTaken,
})}
</p>
)}
{dueContext && (
<p
className="text-muted-foreground text-xs"
@@ -127,6 +127,11 @@ export function LogIntakeDialog({
);
const [skipped, setSkipped] = useState(false);
const [busy, setBusy] = useState(false);
// v1.16.4 — per-intake dose override. `null` = untouched: the slot's
// schedule dose (when a slot is pinned and carries one) or the
// medication's configured dose prefills the field and nothing extra is
// submitted. An edit that deviates travels as `doseTaken`.
const [doseOverride, setDoseOverride] = useState<string | null>(null);
const selected = useMemo(
() => medications.find((m) => m.id === medicationId),
@@ -134,11 +139,30 @@ export function LogIntakeDialog({
);
const slotTimes = useMemo(() => slotTimesFor(selected), [selected]);
// Configured baseline for the picked slot: a pinned slot prefers its
// schedule's own dose (titration schedules differ per slot); otherwise
// the medication's catalogue dose.
const configuredDose = useMemo(() => {
if (!selected) return "";
if (slot !== NO_SLOT) {
const scheduleForSlot = selected.schedules.find((s) =>
s.timesOfDay && s.timesOfDay.length > 0
? s.timesOfDay.includes(slot)
: s.windowStart === slot,
);
if (scheduleForSlot?.dose) return scheduleForSlot.dose;
}
return selected.dose ?? "";
}, [selected, slot]);
const dose = doseOverride ?? configuredDose;
function handleMedicationChange(id: string) {
setMedicationId(id);
// Reset the slot when switching medications — the prior slot may not
// exist on the new schedule.
// exist on the new schedule. The dose override resets too so the new
// medication's configured dose flows through.
setSlot(NO_SLOT);
setDoseOverride(null);
}
async function submit() {
@@ -158,12 +182,20 @@ export function LogIntakeDialog({
scheduledFor = iso;
}
setBusy(true);
// v1.16.4 — only a deliberate deviation travels; an untouched or
// configured-dose value keeps the row NULL (configured dose applies).
const trimmedDose = dose.trim();
const doseDeviates =
!skipped &&
trimmedDose.length > 0 &&
trimmedDose !== configuredDose.trim();
try {
const ok = await runLogIntake({
medication: { id: med.id, name: med.name },
skipped,
takenAt: new Date(takenAt).toISOString(),
scheduledFor,
...(doseDeviates && { doseTaken: trimmedDose }),
t,
queryClient,
});
@@ -214,7 +246,12 @@ export function LogIntakeDialog({
<NativeSelect
id="log-intake-slot"
value={slot}
onChange={(e) => setSlot(e.target.value)}
onChange={(e) => {
setSlot(e.target.value);
// The configured baseline tracks the slot's schedule
// dose, so an untouched field re-prefills on change.
setDoseOverride(null);
}}
>
<option value={NO_SLOT}>
{t("medications.logIntake.slotNone")}
@@ -228,6 +265,24 @@ export function LogIntakeDialog({
</div>
)}
<div className="space-y-2">
<Label htmlFor="log-intake-dose">
{t("medications.logIntake.doseLabel")}
</Label>
<Input
id="log-intake-dose"
value={dose}
maxLength={50}
onChange={(e) => setDoseOverride(e.target.value)}
placeholder={configuredDose}
autoComplete="off"
disabled={skipped}
/>
<p className="text-muted-foreground text-xs">
{t("medications.logIntake.doseHint")}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="log-intake-taken-at">
{t("medications.logIntake.takenAtLabel")}
@@ -181,14 +181,22 @@ export async function runLogIntake(deps: {
* slot. Omit/undefined to route through the unscheduled/PRN path.
*/
scheduledFor?: string;
/**
* v1.16.4 — per-intake dose override. Sent only on a taken write; the
* caller passes it only when the user's dose edit deviates from the
* configured medication / schedule dose.
*/
doseTaken?: string;
t: Translator;
queryClient: QueryClient;
}): Promise<boolean> {
const { medication, skipped, takenAt, scheduledFor, t, queryClient } = deps;
const { medication, skipped, takenAt, scheduledFor, doseTaken, t, queryClient } =
deps;
try {
const body: Record<string, unknown> = { skipped };
if (!skipped) body.takenAt = takenAt;
if (scheduledFor) body.scheduledFor = scheduledFor;
if (!skipped && doseTaken) body.doseTaken = doseTaken;
const res = await fetch(`/api/medications/${medication.id}/intake`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -0,0 +1,70 @@
"use client";
import { ArrowDown, Loader2 } from "lucide-react";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
import type { PullToRefreshState } from "@/hooks/use-pull-to-refresh";
/**
* v1.16.4 — quiet pull-to-refresh affordance for the PWA list pages.
*
* A single small disc that descends from under the app bar as the user
* pulls: an arrow while the gesture is short of the threshold, flipping
* to a spinner once armed / refreshing. Fixed overlay — the page content
* never shifts, so the gesture costs no layout. Renders nothing at rest;
* the disc's opacity tracks the pull so a barely-started drag stays
* barely visible. Touch-only by construction (the hook ignores mouse).
*/
export function PullToRefreshIndicator({
pullDistance,
refreshing,
armed,
threshold,
}: PullToRefreshState) {
const { t } = useTranslations();
if (pullDistance <= 0 && !refreshing) return null;
// Progress drives both the descent and the fade-in; while refreshing the
// disc parks at its full-descent resting point.
const progress = refreshing ? 1 : Math.min(pullDistance / threshold, 1);
const offset = refreshing ? threshold * 0.75 : pullDistance * 0.75;
return (
<div
data-slot="pull-to-refresh-indicator"
role="status"
aria-live="polite"
className="pointer-events-none fixed inset-x-0 top-2 z-50 flex justify-center"
style={{
transform: `translateY(${offset}px)`,
opacity: 0.35 + progress * 0.65,
transition: refreshing ? "transform 150ms ease-out" : undefined,
}}
>
<span
className={cn(
"bg-card text-muted-foreground flex size-8 items-center justify-center rounded-full border shadow-sm",
(armed || refreshing) && "text-primary border-primary/40",
)}
>
{refreshing ? (
<Loader2
className="size-4 animate-spin motion-reduce:animate-none"
aria-hidden="true"
/>
) : (
<ArrowDown
className="size-4 transition-transform duration-150"
style={{ transform: armed ? "rotate(180deg)" : undefined }}
aria-hidden="true"
/>
)}
</span>
<span className="sr-only">
{refreshing ? t("common.pullToRefresh") : null}
</span>
</div>
);
}