Files
HealthLog/src/lib/insights/bmi-status.ts
T
Marc-André BombeckandClaude Opus 4.6 5a71f9b36a refactor(insights): use provider abstraction in all 7 insight generators
Replace direct OpenAI API calls with resolveProvider() in all insight
generators (general, blood-pressure, weight, pulse, bmi, medication-
compliance, mood). Each generator now uses domain-specific prompts from
@/lib/ai/prompts/ and the AIProvider.generateCompletion() interface.
hasKey -> hasProvider in return signatures and all UI consumers.
Remove openaiKeyEncrypted references from data reset routes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 00:42:46 +02:00

300 lines
8.0 KiB
TypeScript

import { prisma } from "@/lib/db";
import { resolveProvider } from "@/lib/ai/provider";
import { getBmiSystemPrompt, getBmiUserPrompt } from "@/lib/ai/prompts/bmi";
import { classifyBMI } from "@/lib/analytics/classifications";
import { getNoKeyBmiStatusText } from "@/lib/insights/no-key-fallbacks";
const BMI_STATUS_POINTS = 30;
const BERLIN_DAY_FORMATTER = new Intl.DateTimeFormat("en-US", {
timeZone: "Europe/Berlin",
year: "numeric",
month: "2-digit",
day: "2-digit",
});
type SupportedLocale = "de" | "en";
function toBerlinDayKey(date: Date): string {
const parts = BERLIN_DAY_FORMATTER.formatToParts(date);
const year = parts.find((part) => part.type === "year")?.value;
const month = parts.find((part) => part.type === "month")?.value;
const day = parts.find((part) => part.type === "day")?.value;
if (!year || !month || !day) {
throw new Error("Could not derive Berlin day key");
}
return `${year}-${month}-${day}`;
}
function round(value: number, digits = 1): number {
const factor = 10 ** digits;
return Math.round(value * factor) / factor;
}
function average(values: number[]): number {
if (values.length === 0) return 0;
return values.reduce((sum, value) => sum + value, 0) / values.length;
}
function normalizeSummaryText(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function normalizeLocale(value: string | null | undefined): SupportedLocale {
return value === "en" ? "en" : "de";
}
function aggregateDailyAverageSeries(
records: Array<{ measuredAt: Date; value: number }>,
) {
const byDay = new Map<string, { sum: number; count: number }>();
for (const record of records) {
const dayKey = toBerlinDayKey(record.measuredAt);
const current = byDay.get(dayKey) ?? { sum: 0, count: 0 };
current.sum += record.value;
current.count += 1;
byDay.set(dayKey, current);
}
return Array.from(byDay.entries())
.sort(([a], [b]) => a.localeCompare(b))
.map(([day, stats]) => ({
day,
value: round(stats.sum / stats.count, 2),
samples: stats.count,
}));
}
function summarizeSeries(series: Array<{ value: number }>) {
if (series.length === 0) return null;
const first = series[0].value;
const last = series[series.length - 1].value;
return {
points: series.length,
start: round(first, 2),
end: round(last, 2),
delta: round(last - first, 2),
mean: round(average(series.map((entry) => entry.value)), 2),
min: round(Math.min(...series.map((entry) => entry.value)), 2),
max: round(Math.max(...series.map((entry) => entry.value)), 2),
};
}
export async function generateBmiStatusForUser(
userId: string,
options?: {
locale?: string | null;
force?: boolean;
},
): Promise<{
hasProvider: boolean;
text: string | null;
cached: boolean;
updatedAt: string | null;
}> {
const locale = normalizeLocale(options?.locale);
const force = options?.force === true;
const cacheAction = `insights.bmi-status.${locale}`;
const todayKey = toBerlinDayKey(new Date());
const provider = await resolveProvider(userId);
if (provider.type === "none") {
return {
hasProvider: false,
text: getNoKeyBmiStatusText(locale),
cached: true,
updatedAt: null,
};
}
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
heightCm: true,
},
});
const latestCache = await prisma.auditLog.findFirst({
where: { userId, action: cacheAction },
orderBy: { createdAt: "desc" },
select: { createdAt: true, details: true },
});
if (!force && latestCache?.details) {
try {
const parsed = JSON.parse(latestCache.details) as {
dateKey?: string;
text?: string;
};
if (
parsed.dateKey === todayKey &&
typeof parsed.text === "string" &&
parsed.text.trim().length > 0
) {
return {
hasProvider: true,
text: parsed.text,
cached: true,
updatedAt: latestCache.createdAt.toISOString(),
};
}
} catch {
// ignore invalid cache payload
}
}
if (!user?.heightCm || user.heightCm <= 0) {
return {
hasProvider: true,
text:
locale === "de"
? "Für die BMI-Einschätzung fehlen aktuell Größenangaben im Profil."
: "BMI assessment currently requires height data in the profile.",
cached: true,
updatedAt: latestCache?.createdAt.toISOString() ?? null,
};
}
const measurements = await prisma.measurement.findMany({
where: {
userId,
type: "WEIGHT",
},
orderBy: { measuredAt: "asc" },
select: {
value: true,
measuredAt: true,
},
});
const weightSeries = aggregateDailyAverageSeries(
measurements.map((measurement) => ({
measuredAt: measurement.measuredAt,
value: measurement.value,
})),
).slice(-BMI_STATUS_POINTS);
const heightFactor = (user.heightCm / 100) ** 2;
const bmiSeries = weightSeries.map((entry) => ({
day: entry.day,
value: round(entry.value / heightFactor, 2),
}));
const latestBmi = bmiSeries.at(-1) ?? null;
const previousBmi = bmiSeries.length > 1 ? (bmiSeries.at(-2) ?? null) : null;
const latestClassification = latestBmi ? classifyBMI(latestBmi.value) : null;
const oldestMeasurement =
measurements.length > 0 ? measurements[0].measuredAt : null;
const newestMeasurement =
measurements.length > 0
? measurements[measurements.length - 1].measuredAt
: null;
const totalSpanDays =
oldestMeasurement && newestMeasurement
? Math.round(
(newestMeasurement.getTime() - oldestMeasurement.getTime()) /
(24 * 60 * 60 * 1000),
)
: 0;
const newestMeasurementDaysAgo = newestMeasurement
? Math.round(
(Date.now() - newestMeasurement.getTime()) / (24 * 60 * 60 * 1000),
)
: null;
const snapshot = {
locale,
generatedForDay: todayKey,
focus: "bmi",
dataCoverage: {
totalMeasurements: measurements.length,
totalSpanDays,
newestMeasurementDaysAgo,
},
bmi: {
summary: summarizeSeries(bmiSeries),
series: bmiSeries,
latestDayFocus: latestBmi
? {
day: latestBmi.day,
value: latestBmi.value,
classification: latestClassification,
deltaToPreviousDailyPoint:
previousBmi == null
? null
: round(latestBmi.value - previousBmi.value, 2),
}
: null,
target: {
greenMin: 18.5,
greenMax: 24.9,
},
},
};
const snapshotJson = JSON.stringify(snapshot, null, 2);
const result = await provider.generateCompletion({
systemPrompt: getBmiSystemPrompt(),
userPrompt: getBmiUserPrompt(snapshotJson, todayKey),
temperature: 0.3,
maxTokens: 1000,
});
const content = result.content;
if (typeof content !== "string" || content.trim().length === 0) {
throw new Error("AI returned empty content for bmi-status");
}
let summary = "";
try {
const parsed = JSON.parse(content) as { summary?: string };
if (typeof parsed.summary === "string") {
summary = parsed.summary;
} else {
summary = content;
}
} catch {
summary = content;
}
summary = normalizeSummaryText(summary);
if (!summary) {
throw new Error("Bmi-status summary was empty after normalization");
}
const created = await prisma.auditLog.create({
data: {
userId,
action: cacheAction,
details: JSON.stringify({
dateKey: todayKey,
locale,
text: summary,
providerType: provider.type,
model: result.model ?? "unknown",
pointsPerMetric: BMI_STATUS_POINTS,
tokensUsed: result.tokensUsed ?? null,
}),
},
select: { createdAt: true },
});
return {
hasProvider: true,
text: summary,
cached: false,
updatedAt: created.createdAt.toISOString(),
};
}
export function resolveBmiStatusLocale(
locale: string | null | undefined,
): SupportedLocale {
return normalizeLocale(locale);
}