fix: i18n completeness + UX polish (closes #73, #74) (#75)

* fix(i18n,ux): package A — missing keys, chart labels, query invalidation, admin error UX

Addresses bugs surfaced in issues #73 and #74 plus drift found during audit.

- i18n: add 21 missing translation keys (targets.* namespace was only
  partially populated after the English-first migration; common.reset and
  settings.configured were referenced but absent), plus common helpers
  (copy, copyDetails, retry, reportIssue) and admin.settingsSaveError.
- charts: rename points7Label/30Label/90Label from cryptic "7P/30P/90P"
  to "7 pts / 30 pts / 90 pts" in EN and "7 Pkt / 30 Pkt / 90 Pkt" in DE.
- queries: add src/lib/query-keys.ts as a single source of truth with
  measurement/mood/medication-dependent key sets. Wire them into
  measurement-form/list, mood-form/list, medication-form/card,
  intake-history-list, intake-timeline, medications page, and Withings
  sync in settings. Fixes dashboard not auto-refreshing after adding a
  measurement (old code only invalidated ["measurements"], not
  ["analytics"] / ["insights"] / ["insights","targets"]).
- admin: useUpdateSettings + updateUser mutations now surface real error
  messages via sonner toasts and invoke getApiErrorMessage() so saves
  fail loudly instead of silently. Success also gets a toast.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(i18n): package B — locale-aware formatters throughout

Removes the hard-coded de-DE locale that lingered from the German-first era
and makes every number, date, and time locale-aware. English stays the
default per user preference; German remains selectable.

New:
- src/lib/format-locale.ts exposes makeFormatters(locale) + a cached
  Europe/Berlin timezone. Covers number, integer, percent, date, dateShort,
  dateTime, time, dateWithWeekday, monthShort. Also exports
  parseLocaleFromAcceptLanguage() for server code.
- useFormatters() hook in @/lib/i18n/context resolves from the active
  locale, memoized per render.

Migrated (all Intl.NumberFormat("de-DE") / toLocaleString("de-DE") /
Intl.DateTimeFormat("de-DE") call sites):
- src/app/page.tsx (dashboard)
- src/app/insights/page.tsx
- src/app/admin/page.tsx
- src/app/settings/page.tsx (Withings last-sync, doctor-report caller)
- src/components/charts/trend-card.tsx (+ i18n "7d"/"30d" short labels)
- src/components/charts/health-chart.tsx
- src/components/medications/medication-card.tsx
- src/components/medications/medication-form.tsx
- src/components/measurements/measurement-list.tsx
- src/components/mood/mood-list.tsx
- src/components/insights/insight-status-card.tsx (also removed 5 German
  hard-coded strings with TODO: i18n markers — now translated)
- src/components/insights/insight-advisor-card.tsx (same — 10+ strings)

Server: reminder-check / reminder-worker / umami-test switched from
"de-DE" to neutral en-GB/en-US where the string is machine-compared rather
than user-facing. Bug-report GitHub issue titles use ISO-8601 UTC now —
the repo is English-speaking.

Next.js metadata:
- OpenGraph locale from "de_DE" → "en_US" with "de_DE" as
  alternateLocale.
- Root layout now reads healthlog-locale cookie (falls back to
  Accept-Language) and sets <html lang> server-side, avoiding an
  EN-flashes-then-DE hydration gap and fixing SEO/a11y.
- I18nProvider mirrors locale to a 1-year SameSite=Lax cookie so the next
  SSR pass is correct.

Doctor-report PDF:
- generateDoctorReportPDF(data, { t, locale }) now accepts injected
  translator + locale. All section titles, column headers, BMI / BP
  classifications, mood labels, and the footer disclaimer are
  i18n-driven. File name slug switches between gesundheitsbericht / health-report.
- 40+ new doctorReport.* keys in EN + DE.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(ux): package C — typed passkey errors, bug-report gating, error boundary

Addresses issue #73 points 1, 5, 6 and lays groundwork for copy-paste
error reporting requested during review.

Passkey registration / login (#73.1):
- src/lib/passkey-errors.ts maps DOMException.name + SimpleWebAuthn code
  to specific i18n keys instead of swallowing every failure as
  "cancelled". Distinguishes NotAllowed/InvalidState/NotSupported/
  Security/Abort errors and falls back to a diagnostic message.
- settings passkey + login passkey flows both use describePasskeyError
  now, so origin mismatches and previous-registration collisions show
  actionable copy.
- 5 new passkey.* i18n keys in EN + DE.

Bug report (#73.5):
- New GET /api/bugreport/status reports {configured, hasToken, hasRepo,
  isAdmin}.
- /bugreport page now queries status first. When not configured it shows
  a notice (different copy for admins vs. regular users) with a direct
  link to the admin panel. Form is hidden, not silently broken.
- When POST /api/bugreport can't create issues it returns 503 instead
  of 500 with the same user-facing message.
- 4 new bugreport.* i18n keys.

Global error UX:
- src/components/error-details.tsx — reusable panel with retry + copy
  diagnostics (message, digest, stack (trimmed), URL, user-agent,
  request-id, locale, timestamp) + report-issue link. Clipboard fallback
  prompt covers insecure-context cases.
- src/app/error.tsx uses it.
- src/app/global-error.tsx is provider-free (no i18n dependency) since
  it replaces the root layout on catastrophic failures — hardcoded
  English + Dracula palette so it still looks like HealthLog.
- 2 new errorBoundary.* keys and 4 common.* keys (copy, copyDetails,
  retry, reportIssue).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor(query-keys): collapse repeated invalidation blocks into invalidateKeys helper

Eleven mutation handlers repeated `Promise.all(keys.map(k => invalidate({queryKey: k})))`
verbatim. Adds `invalidateKeys(qc, keys)` to the existing query-keys factory and
adopts it everywhere, including replacing the local `invalidateMedicationRelated`
helper that medication-form.tsx had grown. Also fixes the import-sandwich that
helper introduced.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* refactor: small simplifications in i18n/UX changes

- passkey-errors: drop the typeof-name dance now that error.name is already string after the instanceof Error narrow
- doctor-report-pdf: replace nested gender ternary with a small lookup map; clarify unitFor's null-as-translation-marker convention
- dashboard page: route the analytics queries through the new queryKeys factory so future invalidation stays in one place
- health-chart: add missing fmt dependency to trendInfo useMemo (introduced when formatSigned was switched to the locale-aware formatter)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(ai): capture upstream response body in OpenAI errors

A production insights burst at 12:19 UTC failed with "OpenAI request
failed (500)". The 500 was the upstream OpenAI HTTP status (confirmed
via logs), but we had no way to tell from logs whether it was an
OpenAI incident, a model-not-found, or a response_format rejection
because the response body was thrown away.

Now the error message includes the first 500 chars of the response body
and structured fields (httpStatus, upstream, model) that Wide Event
logging can attach. No behavior change for the happy path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(review): address code-review + security findings

Review round produced five real issues — fix them all, plus three nits
that were cheap enough to bundle.

Must-fix:
- security: error-details.tsx + global-error.tsx were copying
  window.location.href into the clipboard, which on OAuth callback
  routes (/api/withings/*, password reset) would leak code/state
  tokens into GitHub issues. Strip to pathname + searchParamCount.
- fe: query-keys.invalidateKeys now uses Promise.allSettled, so a
  transient invalidate failure doesn't abort the chain and no
  unhandled rejection leaks from void invalidateKeys(...) call sites.
- fe: resolveInitialLocale in app/layout.tsx wraps cookies()/headers()
  in try/catch — a dynamic-server error in the root layout now
  degrades to the "en" default instead of crashing into global-error.
- be: reminder-worker + reminder-check parseTimeToMinutes normalize
  "24:00" → "00:00" (some ICU builds emit that for midnight under
  en-GB). Prevents a 1440-minute comparison against schedule windows.
- security: openai-client error body excerpt redacts sk-* / Bearer
  tokens before logging, and moves the excerpt off Error.message into
  a structured field (bodyExcerpt) so log transports can filter it.
- i18n: /api/withings/connect German error message → English.
- i18n: /insights/page.tsx hardcoded "Fehler beim Laden" → t(...)

Hardening:
- /api/bugreport/status collapses to {configured, isAdmin} and adds
  a 30/min rate limit per user. Client interface updated.
- i18n/context.tsx: I18nProvider's initializer now reads the cookie
  (matches SSR) before falling back to localStorage or browser
  detection — eliminates the locale-flash hydration class.
- format.ts legacy helpers also read cookie first, matching SSR.

Tests:
- new src/lib/__tests__/format-locale.test.ts — 9 cases covering
  makeFormatters, parseLocaleFromAcceptLanguage, resolveIntlLocale
- new passkey-errors.test.ts — 8 cases covering every DOMException
  name and SimpleWebAuthn code we map
- new query-keys.test.ts — bundles + invalidateKeys allSettled
  semantics (incl. partial-failure test)

118 → 142 tests. All pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Marc-André Bombeck <marc@bombeck.io>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-04-18 17:15:43 +02:00
1 parent cc273216be
commit 9b59390224
46 files changed
+2570 -370

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
import { describe, it, expect } from "vitest";
import {
makeFormatters,
parseLocaleFromAcceptLanguage,
resolveIntlLocale,
} from "../format-locale";
describe("resolveIntlLocale", () => {
it("maps short locales to BCP-47 tags", () => {
expect(resolveIntlLocale("de")).toBe("de-DE");
expect(resolveIntlLocale("en")).toBe("en-US");
});
});
describe("parseLocaleFromAcceptLanguage", () => {
it("returns en for null / empty", () => {
expect(parseLocaleFromAcceptLanguage(null)).toBe("en");
expect(parseLocaleFromAcceptLanguage("")).toBe("en");
});
it("returns de for primary German tag", () => {
expect(parseLocaleFromAcceptLanguage("de-DE,en;q=0.9")).toBe("de");
expect(parseLocaleFromAcceptLanguage("de")).toBe("de");
expect(parseLocaleFromAcceptLanguage("de-CH")).toBe("de");
});
it("returns en for English or unknown locales", () => {
expect(parseLocaleFromAcceptLanguage("en-US,en;q=0.9")).toBe("en");
expect(parseLocaleFromAcceptLanguage("fr-FR,fr;q=0.9")).toBe("en");
expect(parseLocaleFromAcceptLanguage("*")).toBe("en");
});
});
describe("makeFormatters", () => {
const deFmt = makeFormatters("de");
const enFmt = makeFormatters("en");
const sample = new Date("2026-04-18T14:30:00Z"); // 16:30 Europe/Berlin (CEST)
it("formats numbers with regional decimal separators", () => {
expect(deFmt.number(70.5, 1)).toMatch(/70,5/);
expect(enFmt.number(70.5, 1)).toMatch(/70\.5/);
});
it("formats integers with thousands separators", () => {
expect(deFmt.integer(1234567)).toMatch(/1[.\u202f]234[.\u202f]567/);
expect(enFmt.integer(1234567)).toBe("1,234,567");
});
it("formats percent", () => {
expect(deFmt.percent(0.835, 1)).toMatch(/83,5\s*%/);
expect(enFmt.percent(0.835, 1)).toMatch(/83\.5%/);
});
it("formats date in Europe/Berlin", () => {
// Both should include day/month/year; locale-specific order differs.
expect(deFmt.date(sample)).toContain("2026");
expect(enFmt.date(sample)).toContain("2026");
});
it("formats 24h time in Europe/Berlin regardless of locale", () => {
expect(deFmt.time(sample)).toBe("16:30");
expect(enFmt.time(sample)).toBe("16:30");
});
});
+63
View File
@@ -0,0 +1,63 @@
import { describe, it, expect } from "vitest";
import { describePasskeyError } from "../passkey-errors";
function domException(name: string, message = ""): Error {
const err = new Error(message);
err.name = name;
return err;
}
describe("describePasskeyError", () => {
it("returns generic failure for non-Error inputs", () => {
expect(describePasskeyError(undefined)).toEqual({
key: "settings.passkeyRegistrationFailed",
});
expect(describePasskeyError("just a string")).toEqual({
key: "settings.passkeyRegistrationFailed",
});
});
it("maps NotAllowedError to cancelled (the common cancel/timeout case)", () => {
expect(describePasskeyError(domException("NotAllowedError"))).toEqual({
key: "settings.passkeyRegistrationCancelled",
});
});
it("maps InvalidStateError to already-registered", () => {
expect(describePasskeyError(domException("InvalidStateError"))).toEqual({
key: "settings.passkeyAlreadyRegistered",
});
});
it("maps NotSupportedError to not-supported", () => {
expect(describePasskeyError(domException("NotSupportedError"))).toEqual({
key: "settings.passkeyNotSupported",
});
});
it("maps SecurityError to security-blocked", () => {
expect(describePasskeyError(domException("SecurityError"))).toEqual({
key: "settings.passkeySecurityBlocked",
});
});
it("maps AbortError to timeout", () => {
expect(describePasskeyError(domException("AbortError"))).toEqual({
key: "settings.passkeyTimeout",
});
});
it("maps SimpleWebAuthn ERROR_INVALID_RP_ID to security-blocked", () => {
const err = new Error("bad rp");
(err as Error & { code?: string }).code = "ERROR_INVALID_RP_ID";
expect(describePasskeyError(err)).toEqual({
key: "settings.passkeySecurityBlocked",
});
});
it("falls back to unknown with a message param", () => {
const result = describePasskeyError(new Error("mystery failure"));
expect(result.key).toBe("settings.passkeyUnknownError");
expect(result.params).toEqual({ message: "mystery failure" });
});
});
+88
View File
@@ -0,0 +1,88 @@
import { describe, it, expect, vi } from "vitest";
import {
queryKeys,
measurementDependentKeys,
moodDependentKeys,
medicationDependentKeys,
invalidateKeys,
} from "../query-keys";
import type { QueryClient, QueryKey } from "@tanstack/react-query";
describe("queryKeys factory", () => {
it("returns stable tuples for simple keys", () => {
expect(queryKeys.measurements()).toEqual(["measurements"]);
expect(queryKeys.analytics()).toEqual(["analytics"]);
expect(queryKeys.moodEntries()).toEqual(["mood-entries"]);
});
it("includes locale in insights status keys", () => {
expect(queryKeys.insightsGeneralStatus("en")).toEqual([
"insights",
"general-status",
"en",
]);
});
});
describe("dependent-key bundles", () => {
it("measurementDependentKeys invalidates analytics/insights/targets", () => {
const keyStrings = measurementDependentKeys.map((k) =>
JSON.stringify(k),
);
expect(keyStrings).toContain(JSON.stringify(["measurements"]));
expect(keyStrings).toContain(JSON.stringify(["analytics"]));
expect(keyStrings).toContain(JSON.stringify(["insights"]));
expect(keyStrings).toContain(JSON.stringify(["insights", "targets"]));
expect(keyStrings).toContain(
JSON.stringify(["gamification", "achievements"]),
);
});
it("moodDependentKeys bundle covers mood + analytics + targets", () => {
const keyStrings = moodDependentKeys.map((k) => JSON.stringify(k));
expect(keyStrings).toContain(JSON.stringify(["mood-entries"]));
expect(keyStrings).toContain(JSON.stringify(["mood-analytics"]));
expect(keyStrings).toContain(JSON.stringify(["insights"]));
});
it("medicationDependentKeys bundle covers medications + analytics + achievements", () => {
const keyStrings = medicationDependentKeys.map((k) => JSON.stringify(k));
expect(keyStrings).toContain(JSON.stringify(["medications"]));
expect(keyStrings).toContain(JSON.stringify(["analytics"]));
expect(keyStrings).toContain(
JSON.stringify(["gamification", "achievements"]),
);
});
});
describe("invalidateKeys", () => {
it("calls invalidateQueries for every key in the bundle", async () => {
const invalidate = vi.fn().mockResolvedValue(undefined);
const client = { invalidateQueries: invalidate } as unknown as QueryClient;
const keys: QueryKey[] = [["a"], ["b", "c"], ["d"]];
await invalidateKeys(client, keys);
expect(invalidate).toHaveBeenCalledTimes(3);
expect(invalidate).toHaveBeenNthCalledWith(1, { queryKey: ["a"] });
expect(invalidate).toHaveBeenNthCalledWith(2, { queryKey: ["b", "c"] });
expect(invalidate).toHaveBeenNthCalledWith(3, { queryKey: ["d"] });
});
it("continues on partial failure (allSettled semantics)", async () => {
const invalidate = vi
.fn()
.mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(new Error("boom"))
.mockResolvedValueOnce(undefined);
const client = { invalidateQueries: invalidate } as unknown as QueryClient;
const keys: QueryKey[] = [["a"], ["b"], ["c"]];
const results = await invalidateKeys(client, keys);
expect(invalidate).toHaveBeenCalledTimes(3);
expect(results[0].status).toBe("fulfilled");
expect(results[1].status).toBe("rejected");
expect(results[2].status).toBe("fulfilled");
});
});
+20 -1
View File
@@ -36,7 +36,26 @@ export class OpenAIClient implements AIProvider {
});
if (!res.ok) {
throw new Error(`OpenAI request failed (${res.status})`);
// Pull as much of the body as we can so upstream incidents (OpenAI 5xx,
// model-not-found, quota exceeded) are diagnosable from logs instead of
// surfacing as an opaque "OpenAI request failed (500)". Strip anything
// that looks like an API key from the excerpt before logging.
const rawBody = await res.text().catch(() => "");
const bodyExcerpt = rawBody
.slice(0, 500)
.replace(/sk-[A-Za-z0-9_-]{8,}/g, "sk-***redacted***")
.replace(/Bearer\s+[A-Za-z0-9_.-]+/gi, "Bearer ***redacted***");
const err = new Error(`OpenAI request failed (${res.status})`);
// Keep the body in a structured field rather than the message so
// Error.message stays short and the excerpt lands in dedicated log
// fields (bodyExcerpt) that can be filtered/truncated centrally.
Object.assign(err, {
httpStatus: res.status,
upstream: "openai",
model: this.config.model,
bodyExcerpt,
});
throw err;
}
const json = await res.json();
+160 -94
View File
@@ -1,9 +1,15 @@
/**
* Client-side PDF generation for doctor reports.
* Uses jspdf + jspdf-autotable for professional medical-style reports.
*
* Every string and every number/date is driven by an injected `t()` and
* locale-aware formatters so the exported PDF matches the user's UI language.
* Call sites must pass `{ t, locale }` (use the ones from `useTranslations()`
* / `useFormatters()`).
*/
import { jsPDF } from "jspdf";
import autoTable from "jspdf-autotable";
import { makeFormatters } from "./format-locale";
import type { Locale } from "./i18n/config";
interface ReportData {
period: { days: number; since: string };
@@ -40,109 +46,130 @@ interface ReportData {
} | null;
}
const TYPE_LABELS: Record<string, string> = {
WEIGHT: "Körpergewicht",
BLOOD_PRESSURE_SYS: "Systolischer Blutdruck",
BLOOD_PRESSURE_DIA: "Diastolischer Blutdruck",
PULSE: "Ruhepuls",
BODY_FAT: "Körperfettanteil",
SLEEP_DURATION: "Schlafdauer",
ACTIVITY_STEPS: "Aktivität (Schritte)",
type T = (key: string, params?: Record<string, string | number>) => string;
export interface DoctorReportOptions {
t: T;
locale: Locale;
}
const TYPE_LABEL_KEYS: Record<string, string> = {
WEIGHT: "doctorReport.typeWeight",
BLOOD_PRESSURE_SYS: "doctorReport.typeBpSys",
BLOOD_PRESSURE_DIA: "doctorReport.typeBpDia",
PULSE: "doctorReport.typePulse",
BODY_FAT: "doctorReport.typeBodyFat",
SLEEP_DURATION: "doctorReport.typeSleep",
ACTIVITY_STEPS: "doctorReport.typeSteps",
};
const TYPE_UNITS: Record<string, string> = {
const TYPE_UNIT_KEYS: Record<string, string | null> = {
WEIGHT: "kg",
BLOOD_PRESSURE_SYS: "mmHg",
BLOOD_PRESSURE_DIA: "mmHg",
PULSE: "bpm",
BODY_FAT: "%",
SLEEP_DURATION: "h",
ACTIVITY_STEPS: "Schritte",
ACTIVITY_STEPS: null, // translated unit
};
const MOOD_LABELS: Record<number, string> = {
1: "Sehr schlecht",
2: "Schlecht",
3: "Neutral",
4: "Gut",
5: "Sehr gut",
const MOOD_LABEL_KEYS: Record<number, string> = {
1: "doctorReport.moodAwful",
2: "doctorReport.moodBad",
3: "doctorReport.moodNeutral",
4: "doctorReport.moodGood",
5: "doctorReport.moodGreat",
};
function fmt(value: number, decimals = 1): string {
return value.toFixed(decimals).replace(".", ",");
function getBmiClassificationKey(bmi: number): string {
if (bmi < 18.5) return "doctorReport.bmiUnderweight";
if (bmi < 25) return "doctorReport.bmiNormal";
if (bmi < 30) return "doctorReport.bmiOverweight";
if (bmi < 35) return "doctorReport.bmiObeseGrade1";
if (bmi < 40) return "doctorReport.bmiObeseGrade2";
return "doctorReport.bmiObeseGrade3";
}
function formatDate(iso: string): string {
return new Date(iso).toLocaleDateString("de-DE", {
day: "2-digit",
month: "2-digit",
year: "numeric",
});
function getBpClassificationKey(sys: number, dia: number): string {
if (sys < 120 && dia < 80) return "doctorReport.bpOptimal";
if (sys < 130 && dia < 85) return "doctorReport.bpNormal";
if (sys < 140 && dia < 90) return "doctorReport.bpHighNormal";
if (sys < 160 && dia < 100) return "doctorReport.bpHypertensionGrade1";
if (sys < 180 && dia < 110) return "doctorReport.bpHypertensionGrade2";
return "doctorReport.bpHypertensionGrade3";
}
function getBmiClassification(bmi: number): string {
if (bmi < 18.5) return "Untergewicht";
if (bmi < 25) return "Normalgewicht";
if (bmi < 30) return "Übergewicht (Präadipositas)";
if (bmi < 35) return "Adipositas Grad I";
if (bmi < 40) return "Adipositas Grad II";
return "Adipositas Grad III";
}
export function generateDoctorReportPDF(
data: ReportData,
options: DoctorReportOptions,
): jsPDF {
const { t, locale } = options;
const formatters = makeFormatters(locale);
const num = (value: number, decimals = 1) =>
formatters.number(value, decimals);
const fmtDate = (iso: string) => formatters.date(iso);
function getBpClassification(sys: number, dia: number): string {
if (sys < 120 && dia < 80) return "Optimal";
if (sys < 130 && dia < 85) return "Normal";
if (sys < 140 && dia < 90) return "Hochnormal";
if (sys < 160 && dia < 100) return "Hypertonie Grad 1";
if (sys < 180 && dia < 110) return "Hypertonie Grad 2";
return "Hypertonie Grad 3";
}
const unitFor = (type: string): string => {
// Map entry === null means the unit needs translation (e.g. ACTIVITY_STEPS).
const staticUnit = TYPE_UNIT_KEYS[type];
if (staticUnit === null && type === "ACTIVITY_STEPS") {
return t("doctorReport.unitSteps");
}
return staticUnit ?? "";
};
export function generateDoctorReportPDF(data: ReportData): jsPDF {
const doc = new jsPDF({ orientation: "portrait", unit: "mm", format: "a4" });
const pageWidth = doc.internal.pageSize.getWidth();
const margin = 20;
let y = margin;
// ── Header ──────────────────────────────────────────────────────────────
doc.setFontSize(22);
doc.setFont("helvetica", "bold");
doc.setTextColor(30, 30, 30);
doc.text("Gesundheitsbericht", margin, y);
doc.text(t("doctorReport.title"), margin, y);
y += 8;
doc.setFontSize(10);
doc.setFont("helvetica", "normal");
doc.setTextColor(100, 100, 100);
doc.text("HealthLog — Persönlicher Gesundheitsbericht", margin, y);
doc.text(t("doctorReport.subtitle"), margin, y);
y += 6;
// Divider
doc.setDrawColor(200, 200, 200);
doc.setLineWidth(0.5);
doc.line(margin, y, pageWidth - margin, y);
y += 8;
// ── Patient info ────────────────────────────────────────────────────────
doc.setFontSize(9);
doc.setTextColor(80, 80, 80);
const patientInfo: string[] = [];
if (data.patient.username) patientInfo.push(`Patient: ${data.patient.username}`);
if (data.patient.dateOfBirth) {
patientInfo.push(`Geburtsdatum: ${formatDate(data.patient.dateOfBirth)}`);
if (data.patient.username) {
patientInfo.push(`${t("doctorReport.patient")}: ${data.patient.username}`);
}
if (data.patient.gender) {
if (data.patient.dateOfBirth) {
patientInfo.push(
`Geschlecht: ${data.patient.gender === "MALE" ? "Männlich" : data.patient.gender === "FEMALE" ? "Weiblich" : "Divers"}`,
`${t("doctorReport.dateOfBirth")}: ${fmtDate(data.patient.dateOfBirth)}`,
);
}
if (data.patient.gender) {
const genderKeys: Record<string, string> = {
MALE: "doctorReport.genderMale",
FEMALE: "doctorReport.genderFemale",
};
const genderKey = genderKeys[data.patient.gender] ?? "doctorReport.genderOther";
patientInfo.push(`${t("doctorReport.gender")}: ${t(genderKey)}`);
}
if (data.patient.heightCm) {
patientInfo.push(`Körpergröße: ${data.patient.heightCm} cm`);
patientInfo.push(
`${t("doctorReport.height")}: ${data.patient.heightCm} cm`,
);
}
patientInfo.push(
`Berichtszeitraum: ${formatDate(data.period.since)} — ${formatDate(new Date().toISOString())}`,
`${t("doctorReport.period")}: ${fmtDate(data.period.since)} — ${fmtDate(new Date().toISOString())}`,
);
patientInfo.push(
`${t("doctorReport.createdOn")}: ${fmtDate(new Date().toISOString())}`,
);
patientInfo.push(`Erstellt am: ${formatDate(new Date().toISOString())}`);
for (const line of patientInfo) {
doc.text(line, margin, y);
@@ -150,11 +177,10 @@ export function generateDoctorReportPDF(data: ReportData): jsPDF {
}
y += 4;
// ── Vital Signs Summary ─────────────────────────────────────────────────
doc.setFontSize(14);
doc.setFont("helvetica", "bold");
doc.setTextColor(30, 30, 30);
doc.text("Vitalparameter — Übersicht", margin, y);
doc.text(t("doctorReport.vitalsTitle"), margin, y);
y += 6;
const vitalRows: string[][] = [];
@@ -169,20 +195,30 @@ export function generateDoctorReportPDF(data: ReportData): jsPDF {
for (const type of vitalTypes) {
const s = data.stats[type];
if (!s) continue;
const unit = unitFor(type);
vitalRows.push([
TYPE_LABELS[type] || type,
`${fmt(s.latest)} ${TYPE_UNITS[type] || ""}`,
`${fmt(s.avg)} ${TYPE_UNITS[type] || ""}`,
`${fmt(s.min)}`,
`${fmt(s.max)}`,
`${s.count}`,
t(TYPE_LABEL_KEYS[type] ?? ""),
`${num(s.latest)} ${unit}`.trim(),
`${num(s.avg)} ${unit}`.trim(),
num(s.min),
num(s.max),
String(s.count),
]);
}
if (vitalRows.length > 0) {
autoTable(doc, {
startY: y,
head: [["Parameter", "Aktuell", "Ø Zeitraum", "Min", "Max", "n"]],
head: [
[
t("doctorReport.colParameter"),
t("doctorReport.colCurrent"),
t("doctorReport.colAvgPeriod"),
t("doctorReport.colMin"),
t("doctorReport.colMax"),
t("doctorReport.colN"),
],
],
body: vitalRows,
theme: "grid",
styles: {
@@ -200,48 +236,49 @@ export function generateDoctorReportPDF(data: ReportData): jsPDF {
alternateRowStyles: { fillColor: [252, 252, 252] },
margin: { left: margin, right: margin },
});
y = (doc as jsPDF & { lastAutoTable: { finalY: number } }).lastAutoTable
.finalY + 8;
y =
(doc as jsPDF & { lastAutoTable: { finalY: number } }).lastAutoTable
.finalY + 8;
}
// ── Blood Pressure Classification ────────────────────────────────────────
const sysStat = data.stats.BLOOD_PRESSURE_SYS;
const diaStat = data.stats.BLOOD_PRESSURE_DIA;
if (sysStat && diaStat) {
doc.setFontSize(12);
doc.setFont("helvetica", "bold");
doc.text("Blutdruck — ESC/ESH-Klassifikation (2018)", margin, y);
doc.text(t("doctorReport.bpClassificationTitle"), margin, y);
y += 5;
doc.setFontSize(9);
doc.setFont("helvetica", "normal");
const bpClass = getBpClassification(sysStat.avg, diaStat.avg);
const bpClass = t(getBpClassificationKey(sysStat.avg, diaStat.avg));
doc.text(
`Durchschnittlicher Blutdruck: ${fmt(sysStat.avg, 0)}/${fmt(diaStat.avg, 0)} mmHg — Klassifikation: ${bpClass}`,
`${t("doctorReport.avgBp")}: ${num(sysStat.avg, 0)}/${num(diaStat.avg, 0)} mmHg — ${t("doctorReport.classification")}: ${bpClass}`,
margin,
y,
);
y += 8;
}
// ── BMI ──────────────────────────────────────────────────────────────────
if (data.bmi) {
doc.setFontSize(12);
doc.setFont("helvetica", "bold");
doc.text("Body-Mass-Index (BMI)", margin, y);
doc.text(t("doctorReport.bmiTitle"), margin, y);
y += 5;
doc.setFontSize(9);
doc.setFont("helvetica", "normal");
doc.text(
`BMI: ${fmt(data.bmi)} kg/m² — Klassifikation: ${getBmiClassification(data.bmi)} (WHO)`,
t("doctorReport.bmiRow", {
bmi: num(data.bmi, 1),
class: t(getBmiClassificationKey(data.bmi)),
}),
margin,
y,
);
y += 8;
}
// ── Medication Compliance ────────────────────────────────────────────────
const complianceEntries = Object.entries(data.compliance);
if (complianceEntries.length > 0) {
if (y > 240) {
@@ -251,18 +288,33 @@ export function generateDoctorReportPDF(data: ReportData): jsPDF {
doc.setFontSize(14);
doc.setFont("helvetica", "bold");
doc.text("Medikamenten-Compliance", margin, y);
doc.text(t("doctorReport.complianceTitle"), margin, y);
y += 6;
const compRows = complianceEntries.map(([name, c]) => {
const rate = c.total > 0 ? ((c.taken / c.total) * 100).toFixed(1) : "—";
return [name, `${c.taken}`, `${c.skipped}`, `${c.missed}`, `${c.total}`, `${rate}%`];
const rate =
c.total > 0 ? `${num((c.taken / c.total) * 100, 1)}%` : "—";
return [
name,
String(c.taken),
String(c.skipped),
String(c.missed),
String(c.total),
rate,
];
});
autoTable(doc, {
startY: y,
head: [
["Medikament", "Eingenommen", "Übersprungen", "Verpasst", "Gesamt", "Compliance-Rate"],
[
t("doctorReport.colMedication"),
t("doctorReport.colTaken"),
t("doctorReport.colSkipped"),
t("doctorReport.colMissed"),
t("doctorReport.colTotal"),
t("doctorReport.colComplianceRate"),
],
],
body: compRows,
theme: "grid",
@@ -281,11 +333,11 @@ export function generateDoctorReportPDF(data: ReportData): jsPDF {
alternateRowStyles: { fillColor: [252, 252, 252] },
margin: { left: margin, right: margin },
});
y = (doc as jsPDF & { lastAutoTable: { finalY: number } }).lastAutoTable
.finalY + 8;
y =
(doc as jsPDF & { lastAutoTable: { finalY: number } }).lastAutoTable
.finalY + 8;
}
// ── Mood ─────────────────────────────────────────────────────────────────
if (data.mood) {
if (y > 240) {
doc.addPage();
@@ -294,13 +346,18 @@ export function generateDoctorReportPDF(data: ReportData): jsPDF {
doc.setFontSize(14);
doc.setFont("helvetica", "bold");
doc.text("Stimmungsverlauf", margin, y);
doc.text(t("doctorReport.moodTitle"), margin, y);
y += 6;
doc.setFontSize(9);
doc.setFont("helvetica", "normal");
doc.text(
`Durchschnitt: ${fmt(data.mood.avg)} / 5,0 | Einträge: ${data.mood.count} | Bereich: ${data.mood.min} – ${data.mood.max}`,
t("doctorReport.moodSummary", {
avg: num(data.mood.avg, 1),
count: data.mood.count,
min: num(data.mood.min, 0),
max: num(data.mood.max, 0),
}),
margin,
y,
);
@@ -308,15 +365,23 @@ export function generateDoctorReportPDF(data: ReportData): jsPDF {
const distRows = Object.entries(data.mood.distribution).map(
([score, count]) => [
MOOD_LABELS[Number(score)] || score,
`${count}`,
`${data.mood!.count > 0 ? ((count / data.mood!.count) * 100).toFixed(1) : 0}%`,
t(MOOD_LABEL_KEYS[Number(score)] ?? "doctorReport.moodNeutral"),
String(count),
data.mood!.count > 0
? `${num((count / data.mood!.count) * 100, 1)}%`
: "0%",
],
);
autoTable(doc, {
startY: y,
head: [["Stimmung", "Anzahl", "Anteil"]],
head: [
[
t("doctorReport.colMood"),
t("doctorReport.colCount"),
t("doctorReport.colShare"),
],
],
body: distRows,
theme: "grid",
styles: {
@@ -333,34 +398,35 @@ export function generateDoctorReportPDF(data: ReportData): jsPDF {
},
margin: { left: margin, right: margin },
});
y = (doc as jsPDF & { lastAutoTable: { finalY: number } }).lastAutoTable
.finalY + 8;
y =
(doc as jsPDF & { lastAutoTable: { finalY: number } }).lastAutoTable
.finalY + 8;
}
// ── Footer / Disclaimer ──────────────────────────────────────────────────
const addFooter = (pageDoc: jsPDF) => {
const pageHeight = pageDoc.internal.pageSize.getHeight();
pageDoc.setFontSize(7);
pageDoc.setFont("helvetica", "italic");
pageDoc.setTextColor(140, 140, 140);
pageDoc.text(
"Dieser Bericht wurde automatisch aus selbst erfassten Daten generiert und dient ausschließlich zur Unterstützung",
t("doctorReport.footerDisclaimer1"),
margin,
pageHeight - 14,
);
pageDoc.text(
"des Arzt-Patienten-Gesprächs. Er ersetzt keine ärztliche Diagnose. Korrelationen implizieren keine Kausalität.",
t("doctorReport.footerDisclaimer2"),
margin,
pageHeight - 10,
);
pageDoc.text(
`Quelle: HealthLog | Zeitzone: Europe/Berlin | Erstellt: ${new Date().toLocaleString("de-DE", { timeZone: "Europe/Berlin" })}`,
t("doctorReport.footerSource", {
timestamp: formatters.dateTime(new Date()),
}),
margin,
pageHeight - 6,
);
};
// Add footer to all pages
const totalPages = doc.getNumberOfPages();
for (let i = 1; i <= totalPages; i++) {
doc.setPage(i);
+144
View File
@@ -0,0 +1,144 @@
/**
* Locale-aware formatters.
*
* HealthLog's UI language is user-configurable (DE/EN). Numbers, dates, and
* times must render in the active locale — not in the hard-coded de-DE that
* lingered from the German-first era.
*
* Call via the `useFormatters()` client hook. For server-only code paths
* (jobs, API routes, PDF generation) pass the locale explicitly through
* `makeFormatters(locale)`.
*
* Timezone is fixed to Europe/Berlin for display (user expectation). UTC is
* preserved in the database.
*/
import type { Locale } from "./i18n/config";
export const DISPLAY_TIMEZONE = "Europe/Berlin";
/**
* Map our short locale ("de" / "en") to a full BCP-47 tag suitable for
* `Intl.*`. When we add locales, extend this map — do not rely on the short
* tag directly since browsers differ in how they handle "en" vs "en-US".
*/
export const INTL_LOCALE_MAP: Record<Locale, string> = {
de: "de-DE",
en: "en-US",
};
export function resolveIntlLocale(locale: Locale): string {
return INTL_LOCALE_MAP[locale] ?? "en-US";
}
type DateInput = Date | string | number;
function asDate(value: DateInput): Date {
return value instanceof Date ? value : new Date(value);
}
export interface Formatters {
/** Integer or decimal with the active locale's decimal separator. */
number: (value: number, fractionDigits?: number) => string;
/** Same as `number` but thousands-grouped. */
integer: (value: number) => string;
/** Percentage, e.g. 0.835 → "83,5 %" in DE / "83.5%" in EN. */
percent: (value: number, fractionDigits?: number) => string;
/** Short date, e.g. "19.02.2026" / "02/19/2026". */
date: (value: DateInput) => string;
/** Short date without year, e.g. "19.02." / "Feb 19". */
dateShort: (value: DateInput) => string;
/** Full date + time in 24h. */
dateTime: (value: DateInput) => string;
/** Time only in 24h, e.g. "14:30". */
time: (value: DateInput) => string;
/** Short weekday + date, e.g. "Do., 19.02." / "Thu, Feb 19". */
dateWithWeekday: (value: DateInput) => string;
/** For axis labels: 3-letter month abbreviation. */
monthShort: (value: DateInput) => string;
}
export function makeFormatters(locale: Locale): Formatters {
const intlLocale = resolveIntlLocale(locale);
const tz = DISPLAY_TIMEZONE;
return {
number: (value, fractionDigits) =>
new Intl.NumberFormat(intlLocale, {
minimumFractionDigits: fractionDigits,
maximumFractionDigits: fractionDigits,
}).format(value),
integer: (value) =>
new Intl.NumberFormat(intlLocale, { maximumFractionDigits: 0 }).format(
value,
),
percent: (value, fractionDigits = 0) =>
new Intl.NumberFormat(intlLocale, {
style: "percent",
minimumFractionDigits: fractionDigits,
maximumFractionDigits: fractionDigits,
}).format(value),
date: (value) =>
asDate(value).toLocaleDateString(intlLocale, {
timeZone: tz,
day: "2-digit",
month: "2-digit",
year: "numeric",
}),
dateShort: (value) =>
asDate(value).toLocaleDateString(intlLocale, {
timeZone: tz,
day: "2-digit",
month: "2-digit",
}),
dateTime: (value) =>
asDate(value).toLocaleString(intlLocale, {
timeZone: tz,
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
hour12: false,
}),
time: (value) =>
asDate(value).toLocaleTimeString(intlLocale, {
timeZone: tz,
hour: "2-digit",
minute: "2-digit",
hour12: false,
}),
dateWithWeekday: (value) =>
asDate(value).toLocaleDateString(intlLocale, {
timeZone: tz,
weekday: "short",
day: "2-digit",
month: "2-digit",
}),
monthShort: (value) =>
asDate(value).toLocaleDateString(intlLocale, {
timeZone: tz,
month: "short",
}),
};
}
/**
* Parse locale from a `Accept-Language` header or `healthlog-locale` cookie.
* Server-side helper for jobs, API routes, and PDF generation where there is
* no React context.
*/
export function parseLocaleFromAcceptLanguage(header: string | null): Locale {
if (!header) return "en";
const primary = header.split(",")[0]?.trim().toLowerCase() ?? "";
if (primary.startsWith("de")) return "de";
return "en";
}
+46 -42
View File
@@ -1,63 +1,67 @@
/**
* Consistent date/time formatting for the HealthLog UI.
* All functions use de-DE locale, Europe/Berlin timezone, 24h format.
* Legacy locale-aware date/time helpers.
*
* These originally hard-coded `de-DE`. They now defer to `makeFormatters`
* using a best-effort read of `healthlog-locale` from cookie → localStorage,
* falling back to `en`. New code should prefer `useFormatters()` from
* `@/lib/i18n/context` (client) or `makeFormatters(locale)` from
* `@/lib/format-locale` (server).
*
* SSR caveat: on the server `activeLocale()` always returns `en` because
* `document` is undefined. All current call sites render their formatted
* strings only after a `useQuery` fetch — i.e. post-hydration — so there is
* no hydration-mismatch path today. If you add a new caller that renders
* pre-fetch data (e.g. a static prop), migrate it to `useFormatters()` to
* stay consistent with the server-rendered locale.
*/
const TIMEZONE = "Europe/Berlin";
const LOCALE = "de-DE";
import { makeFormatters, DISPLAY_TIMEZONE } from "./format-locale";
import type { Locale } from "./i18n/config";
/** "19.02.2026, 14:30" */
export { DISPLAY_TIMEZONE };
function activeLocale(): Locale {
if (typeof document === "undefined") return "en";
// Prefer the cookie (what SSR used) over localStorage to stay in sync
// across hydration. Falls back to localStorage for backwards compat.
const cookieMatch = document.cookie.match(
/(?:^|;\s*)healthlog-locale=([^;]+)/,
);
const fromCookie = cookieMatch?.[1];
if (fromCookie === "de" || fromCookie === "en") return fromCookie;
const fromStorage = window.localStorage?.getItem("healthlog-locale");
return fromStorage === "de" ? "de" : "en";
}
function formatters() {
return makeFormatters(activeLocale());
}
/** Locale-aware "19.02.2026, 14:30" or "02/19/2026, 2:30 PM". */
export function formatDateTime(date: Date | string): string {
return new Date(date).toLocaleString(LOCALE, {
timeZone: TIMEZONE,
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
return formatters().dateTime(date);
}
/** "19.02.2026" */
/** Locale-aware "19.02.2026" or "02/19/2026". */
export function formatDate(date: Date | string): string {
return new Date(date).toLocaleDateString(LOCALE, {
timeZone: TIMEZONE,
day: "2-digit",
month: "2-digit",
year: "numeric",
});
return formatters().date(date);
}
/** "19.02." or "19.02.2026" if includeYear */
/** Locale-aware short date without year unless `includeYear`. */
export function formatDateShort(
date: Date | string,
includeYear = false,
): string {
return new Date(date).toLocaleDateString(LOCALE, {
timeZone: TIMEZONE,
day: "2-digit",
month: "2-digit",
...(includeYear ? { year: "numeric" } : {}),
});
const f = formatters();
return includeYear ? f.date(date) : f.dateShort(date);
}
/** "14:30" */
/** Locale-aware "14:30". */
export function formatTime(date: Date | string): string {
return new Date(date).toLocaleTimeString(LOCALE, {
timeZone: TIMEZONE,
hour: "2-digit",
minute: "2-digit",
hour12: false,
});
return formatters().time(date);
}
/** "Do., 19.02." */
/** Locale-aware short weekday + date. */
export function formatDateWithWeekday(date: Date | string): string {
return new Date(date).toLocaleDateString(LOCALE, {
timeZone: TIMEZONE,
weekday: "short",
day: "2-digit",
month: "2-digit",
});
return formatters().dateWithWeekday(date);
}
+34 -1
View File
@@ -4,11 +4,13 @@ import {
createContext,
useContext,
useEffect,
useMemo,
useState,
useCallback,
type ReactNode,
} from "react";
import { locales, defaultLocale, type Locale } from "./config";
import { makeFormatters, type Formatters } from "../format-locale";
import deMessages from "../../../messages/de.json";
import enMessages from "../../../messages/en.json";
@@ -53,8 +55,23 @@ function detectSystemLocale(): Locale {
: defaultLocale;
}
function readLocaleCookie(): Locale | null {
if (typeof document === "undefined") return null;
const match = document.cookie.match(/(?:^|;\s*)healthlog-locale=([^;]+)/);
const value = match?.[1];
if (value && (locales as readonly string[]).includes(value)) {
return value as Locale;
}
return null;
}
function getSavedLocale(): Locale | null {
if (typeof window === "undefined") return null;
// Cookie wins over localStorage: the root layout already rendered the
// server HTML using the cookie, so matching the cookie on first client
// render avoids a hydration flash of the wrong language.
const fromCookie = readLocaleCookie();
if (fromCookie) return fromCookie;
const saved = localStorage.getItem("healthlog-locale");
if (saved && (locales as readonly string[]).includes(saved)) {
return saved as Locale;
@@ -71,13 +88,19 @@ export function I18nProvider({ children }: { children: ReactNode }) {
if ((locales as readonly string[]).includes(newLocale)) {
setLocaleState(newLocale);
localStorage.setItem("healthlog-locale", newLocale);
// Also mirror to cookie so SSR (layout, metadata) renders in the
// user's language. 1-year expiry, Lax samesite, not HttpOnly so the
// client continues to own it.
document.cookie = `healthlog-locale=${newLocale}; path=/; max-age=${60 * 60 * 24 * 365}; SameSite=Lax`;
document.documentElement.lang = newLocale;
}
}, []);
// Set HTML lang on mount
// Keep the HTML lang and the cookie in sync with the active locale on
// mount. The cookie acts as the SSR handoff for the next request.
useEffect(() => {
document.documentElement.lang = locale;
document.cookie = `healthlog-locale=${locale}; path=/; max-age=${60 * 60 * 24 * 365}; SameSite=Lax`;
}, [locale]);
const t = useCallback(
@@ -120,3 +143,13 @@ export function useTranslations() {
}
return context;
}
/**
* Locale-aware formatters tied to the active UI locale. Use for every number,
* date, and time rendered in the UI so regional conventions (70,5 vs 70.5,
* 19.02.2026 vs Feb 19, 2026) follow the user's language choice.
*/
export function useFormatters(): Formatters {
const { locale } = useTranslations();
return useMemo(() => makeFormatters(locale), [locale]);
}
+6 -2
View File
@@ -46,7 +46,11 @@ import {
function parseTimeToMinutes(value: string): number {
const [h, m] = value.split(":").map(Number);
if (!Number.isFinite(h) || !Number.isFinite(m)) return 0;
return h * 60 + m;
// Some Node ICU builds render midnight as "24:00" via toLocaleTimeString.
// Normalize so comparisons against schedule windows that wrap midnight
// don't produce a 1440-minute value.
const hours = h === 24 ? 0 : h;
return hours * 60 + m;
}
const DATABASE_URL = process.env.DATABASE_URL!;
@@ -259,7 +263,7 @@ async function handleReminderCheck(jobs: Job<ReminderCheckPayload>[]) {
userTz,
);
const currentTime = now.toLocaleTimeString("de-DE", {
const currentTime = now.toLocaleTimeString("en-GB", {
timeZone: userTz,
hour: "2-digit",
minute: "2-digit",
+49
View File
@@ -0,0 +1,49 @@
/**
* Map WebAuthn / SimpleWebAuthn errors to actionable i18n keys.
*
* The browser rejects passkey prompts for several reasons that feel
* indistinguishable to the user. We preserve the real reason so
* "registration cancelled" no longer masks "your origin isn't HTTPS" or
* "this device is already registered".
*/
export interface PasskeyErrorMessage {
/** i18n key for a user-facing explanation. */
key: string;
/** Params for interpolation (e.g. {message} for the unknown-error case). */
params?: Record<string, string>;
}
export function describePasskeyError(error: unknown): PasskeyErrorMessage {
if (!(error instanceof Error)) {
return { key: "settings.passkeyRegistrationFailed" };
}
// SimpleWebAuthn wraps DOMException into WebAuthnError with a `code`
// property, but the underlying DOMException name is the stable signal.
switch (error.name) {
case "NotAllowedError":
// The user cancelled, or the OS-level prompt timed out. Prefer the
// cancelled copy — it matches what the user did in the common case.
return { key: "settings.passkeyRegistrationCancelled" };
case "InvalidStateError":
return { key: "settings.passkeyAlreadyRegistered" };
case "NotSupportedError":
return { key: "settings.passkeyNotSupported" };
case "SecurityError":
return { key: "settings.passkeySecurityBlocked" };
case "AbortError":
return { key: "settings.passkeyTimeout" };
}
// SimpleWebAuthn WebAuthnError surfaces a `code`, e.g. "ERROR_INVALID_RP_ID"
const code = (error as { code?: string }).code;
if (code === "ERROR_INVALID_RP_ID" || code === "ERROR_INVALID_DOMAIN") {
return { key: "settings.passkeySecurityBlocked" };
}
return {
key: "settings.passkeyUnknownError",
params: { message: error.message || "unknown" },
};
}
+124
View File
@@ -0,0 +1,124 @@
/**
* Centralized TanStack Query key factory.
*
* Every useQuery/invalidateQueries call should go through this factory so that
* mutations invalidate the right consumers. Hard-coded string arrays drifted in
* the past (e.g. ["measurements"] didn't invalidate ["analytics"] on the
* dashboard), so treat this file as the single source of truth.
*/
import type { QueryClient, QueryKey } from "@tanstack/react-query";
export const queryKeys = {
auth: () => ["auth"] as const,
authRegistrationStatus: () => ["auth", "registration-status"] as const,
measurements: () => ["measurements"] as const,
moodEntries: () => ["mood-entries"] as const,
analytics: () => ["analytics"] as const,
moodAnalytics: () => ["mood-analytics"] as const,
insightsRoot: () => ["insights"] as const,
insightsComprehensive: () => ["insights", "comprehensive"] as const,
insightsTargets: () => ["insights", "targets"] as const,
insightsGeneralStatus: (locale: string) =>
["insights", "general-status", locale] as const,
insightsBpStatus: (locale: string) =>
["insights", "blood-pressure-status", locale] as const,
insightsWeightStatus: (locale: string) =>
["insights", "weight-status", locale] as const,
insightsPulseStatus: (locale: string) =>
["insights", "pulse-status", locale] as const,
insightsBmiStatus: (locale: string) =>
["insights", "bmi-status", locale] as const,
insightsMoodStatus: (locale: string) =>
["insights", "mood-status", locale] as const,
insightsMedicationComplianceStatus: (locale: string) =>
["insights", "medication-compliance-status", locale] as const,
medications: () => ["medications"] as const,
medicationDetail: (id: string) => ["medications", id] as const,
medicationComplianceChart: (medicationId: string) =>
["compliance-chart-inline", medicationId] as const,
medicationPhaseConfig: (medicationId: string) =>
["phase-config", medicationId] as const,
medicationIntakeSummary: () => ["medications", "intake-summary"] as const,
gamificationAchievements: () => ["gamification", "achievements"] as const,
passkeys: () => ["passkeys"] as const,
notificationsPreferences: () => ["notifications", "preferences"] as const,
settingsGlobalServices: () => ["settings", "global-services"] as const,
settingsNtfy: () => ["settings", "ntfy"] as const,
tokens: () => ["tokens"] as const,
telegram: () => ["telegram"] as const,
telegramSettings: () => ["telegram", "settings"] as const,
withings: () => ["withings"] as const,
adminSettings: () => ["admin", "settings"] as const,
adminStatus: () => ["admin", "status"] as const,
adminUsers: () => ["admin", "users"] as const,
adminTokens: () => ["admin", "tokens"] as const,
adminAuditLog: (filter: unknown) => ["admin", "audit-log", filter] as const,
bugreportStatus: () => ["bugreport", "status"] as const,
};
/**
* Keys that should be invalidated when a measurement is created, updated or
* deleted. Kept here so dashboards, insights, and targets always stay in sync.
*/
export const measurementDependentKeys = [
queryKeys.measurements(),
queryKeys.analytics(),
queryKeys.insightsRoot(),
queryKeys.insightsTargets(),
queryKeys.gamificationAchievements(),
];
/**
* Keys that should be invalidated when a mood entry is created, updated or
* deleted.
*/
export const moodDependentKeys = [
queryKeys.moodEntries(),
queryKeys.moodAnalytics(),
queryKeys.insightsRoot(),
queryKeys.insightsTargets(),
queryKeys.gamificationAchievements(),
];
/**
* Keys invalidated when medications change (CRUD or intake).
*/
export const medicationDependentKeys = [
queryKeys.medications(),
queryKeys.analytics(),
queryKeys.insightsRoot(),
queryKeys.insightsTargets(),
queryKeys.medicationIntakeSummary(),
queryKeys.gamificationAchievements(),
];
/**
* Invalidate every key in the bundle in parallel. Use this from mutation
* `onSuccess` handlers so the call site stays a one-liner instead of repeating
* `Promise.all(keys.map(...))` everywhere.
*
* Uses `allSettled` so one transient network failure doesn't abort subsequent
* invalidations (cache would otherwise be left half-stale) and so the `void
* invalidateKeys(...)` fire-and-forget pattern in delete handlers never
* surfaces an unhandled rejection.
*/
export function invalidateKeys(
queryClient: QueryClient,
keys: readonly QueryKey[],
): Promise<PromiseSettledResult<unknown>[]> {
return Promise.allSettled(
keys.map((queryKey) => queryClient.invalidateQueries({ queryKey })),
);
}