feat(import): show lab results from health records under an Apple Health import

A finished import now lists the lab results it found next to the ECG
line, and an archive whose only new data is lab results no longer says
nothing was imported. The status endpoint bounds the lab counts the
same way it bounds the ECG counts.
This commit is contained in:
Marc-André Bombeck committed 2026-11-17 18:46:27 +01:00
1 parent 736e6e9c86
commit 14c3c6696a
15 files changed
+166 -30

No files matched your search

+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "{count} Einträge, die HealthLog selbst in Apple Health geschrieben hat, wurden ausgelassen, weil sie schon in deinen Daten sind.",
"writtenByHealthLogFew": "{count} Einträge, die HealthLog selbst in Apple Health geschrieben hat, wurden ausgelassen, weil sie schon in deinen Daten sind.",
"ecgResult": "EKGs: {discovered} gefunden, {imported} importiert, {updated} aktualisiert, {skipped} übersprungen, {failed} fehlgeschlagen. Fehler bei EKGs verwerfen keine unterstützten Datensätze, die aus export.xml importiert wurden.",
"labsResult": "Laborwerte aus Gesundheitsakten: {discovered} gefunden, {imported} importiert, {duplicate} schon vorhanden, {skipped} übersprungen, {failed} fehlgeschlagen. Ein fehlgeschlagener Laborwert verwirft nichts anderes aus dem Archiv.",
"estimateWarning": "Kumulative Summen für {count} Tag(e) wurden anhand der größten Exportquelle geschätzt. Native Apple-Health-Statistiken bleiben maßgeblich.",
"phase": {
"queued": "In Warteschlange…",
+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "{count} records that HealthLog wrote into Apple Health itself were left out, because they are already in your data.",
"writtenByHealthLogFew": "{count} records that HealthLog wrote into Apple Health itself were left out, because they are already in your data.",
"ecgResult": "ECGs: {discovered} discovered, {imported} imported, {updated} updated, {skipped} skipped, {failed} failed. ECG failures do not discard supported records imported from export.xml.",
"labsResult": "Lab results from health records: {discovered} found, {imported} imported, {duplicate} already in your record, {skipped} skipped, {failed} failed. A lab result that fails does not discard anything else from the archive.",
"estimateWarning": "Cumulative totals for {count} day(s) were estimated from the largest export source. Native Apple Health statistics remain authoritative.",
"phase": {
"queued": "Queued…",
+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "Se omitieron {count} registros que HealthLog escribió en Apple Health, porque ya están en tus datos.",
"writtenByHealthLogFew": "Se omitieron {count} registros que HealthLog escribió en Apple Health, porque ya están en tus datos.",
"ecgResult": "ECG: {discovered} detectados, {imported} importados, {updated} actualizados, {skipped} omitidos y {failed} fallidos. Los errores de ECG no descartan los registros compatibles importados desde export.xml.",
"labsResult": "Resultados de laboratorio de los registros de salud: {discovered} detectados, {imported} importados, {duplicate} ya registrados, {skipped} omitidos y {failed} fallidos. Un resultado que falla no descarta nada más del archivo.",
"estimateWarning": "Los totales acumulados de {count} día(s) se estimaron a partir de la mayor fuente de la exportación. Las estadísticas nativas de Apple Health siguen siendo la referencia.",
"phase": {
"queued": "En cola…",
+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "{count} enregistrements que HealthLog a écrits lui-même dans Santé ont été ignorés, car ils figurent déjà dans vos données.",
"writtenByHealthLogFew": "{count} enregistrements que HealthLog a écrits lui-même dans Santé ont été ignorés, car ils figurent déjà dans vos données.",
"ecgResult": "ECG : {discovered} détectés, {imported} importés, {updated} mis à jour, {skipped} ignorés et {failed} échoués. Les erreurs d’ECG n’annulent pas les enregistrements compatibles importés depuis export.xml.",
"labsResult": "Résultats d’analyses des dossiers médicaux : {discovered} détectés, {imported} importés, {duplicate} déjà enregistrés, {skipped} ignorés et {failed} échoués. Un résultat en échec n’annule rien d’autre dans l’archive.",
"estimateWarning": "Les totaux cumulés de {count} jour(s) ont été estimés à partir de la source d’export la plus élevée. Les statistiques Apple Santé natives restent la référence.",
"phase": {
"queued": "En file d'attente…",
+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "{count} registrazioni che HealthLog ha scritto in Salute sono state escluse, perché sono già nei tuoi dati.",
"writtenByHealthLogFew": "{count} registrazioni che HealthLog ha scritto in Salute sono state escluse, perché sono già nei tuoi dati.",
"ecgResult": "ECG: {discovered} rilevati, {imported} importati, {updated} aggiornati, {skipped} ignorati e {failed} non riusciti. Gli errori ECG non eliminano i record supportati importati da export.xml.",
"labsResult": "Esami di laboratorio dalle cartelle cliniche: {discovered} rilevati, {imported} importati, {duplicate} già presenti, {skipped} ignorati e {failed} non riusciti. Un esame non riuscito non elimina nient’altro dall’archivio.",
"estimateWarning": "I totali cumulativi di {count} giorno/i sono stati stimati dalla fonte di esportazione più alta. Le statistiche native di Apple Salute restano autorevoli.",
"phase": {
"queued": "In coda…",
+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "HealthLog가 직접 건강 앱에 기록한 {count}개 항목은 이미 데이터에 있으므로 제외했습니다.",
"writtenByHealthLogFew": "HealthLog가 직접 건강 앱에 기록한 {count}개 항목은 이미 데이터에 있으므로 제외했습니다.",
"ecgResult": "심전도: 발견 {discovered}개, 불러옴 {imported}개, 갱신 {updated}개, 건너뜀 {skipped}개, 실패 {failed}개. 심전도가 실패해도 export.xml에서 불러온 지원 기록은 그대로 남아요.",
"labsResult": "건강 기록의 검사 결과: 발견 {discovered}개, 불러옴 {imported}개, 이미 있음 {duplicate}개, 건너뜀 {skipped}개, 실패 {failed}개. 검사 결과가 실패해도 아카이브의 다른 기록은 그대로 남아요.",
"estimateWarning": "{count}일치 누적 합계는 가장 큰 내보내기 소스에서 추정했어요. Apple Health 자체 통계가 여전히 기준이에요.",
"phase": {
"queued": "대기 중…",
+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "{count} records die HealthLog zelf naar Apple Health had geschreven, zijn weggelaten, omdat ze al in je gegevens staan.",
"writtenByHealthLogFew": "{count} records die HealthLog zelf naar Apple Health had geschreven, zijn weggelaten, omdat ze al in je gegevens staan.",
"ecgResult": "ECG's: {discovered} gevonden, {imported} geïmporteerd, {updated} bijgewerkt, {skipped} overgeslagen, {failed} mislukt. Mislukte ECG's maken ondersteunde records die uit export.xml zijn geïmporteerd niet ongedaan.",
"labsResult": "Labuitslagen uit medische dossiers: {discovered} gevonden, {imported} geïmporteerd, {duplicate} al aanwezig, {skipped} overgeslagen, {failed} mislukt. Een mislukte uitslag gooit verder niets uit het archief weg.",
"estimateWarning": "Cumulatieve totalen voor {count} dag(en) zijn geschat op basis van de grootste bron in de export. De eigen statistieken van Apple Health blijven leidend.",
"phase": {
"queued": "In de wachtrij…",
+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "Pominięto {count} wpisów, które HealthLog sam zapisał w Apple Health, ponieważ są już w Twoich danych.",
"writtenByHealthLogFew": "Pominięto {count} wpisy, które HealthLog sam zapisał w Apple Health, ponieważ są już w Twoich danych.",
"ecgResult": "EKG: wykryto {discovered}, zaimportowano {imported}, zaktualizowano {updated}, pominięto {skipped}, nie powiodło się {failed}. Błędy EKG nie usuwają obsługiwanych rekordów zaimportowanych z pliku export.xml.",
"labsResult": "Wyniki badań z dokumentacji medycznej: wykryto {discovered}, zaimportowano {imported}, już zapisane {duplicate}, pominięto {skipped}, nie powiodło się {failed}. Nieudany wynik nie usuwa niczego innego z archiwum.",
"estimateWarning": "Łączne wartości dla {count} dni oszacowano na podstawie największego źródła w eksporcie. Natywne statystyki Apple Health pozostają nadrzędne.",
"phase": {
"queued": "W kolejce…",
+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "{count} registros que o próprio HealthLog gravou no Apple Health foram deixados de fora, porque já estão nos seus dados.",
"writtenByHealthLogFew": "{count} registros que o próprio HealthLog gravou no Apple Health foram deixados de fora, porque já estão nos seus dados.",
"ecgResult": "ECGs: {discovered} descobertos, {imported} importados, {updated} atualizados, {skipped} pulados, {failed} falharam. Falhas de ECG não descartam registros compatíveis importados do export.xml.",
"labsResult": "Resultados de exames dos registros de saúde: {discovered} descobertos, {imported} importados, {duplicate} já registrados, {skipped} pulados, {failed} falharam. Um resultado com falha não descarta mais nada do arquivo.",
"estimateWarning": "Os totais acumulados de {count} dia(s) foram estimados a partir da maior fonte de exportação. As estatísticas nativas do Apple Health continuam sendo a referência.",
"phase": {
"queued": "Na fila…",
+1
View File
@@ -5895,6 +5895,7 @@
"writtenByHealthLogOther": "{count} записей, которые HealthLog сам записал в Apple Health, были исключены, потому что они уже есть в ваших данных.",
"writtenByHealthLogFew": "{count} записи, которые HealthLog сам записал в Apple Health, были исключены, потому что они уже есть в ваших данных.",
"ecgResult": "ЭКГ: обнаружено {discovered}, импортировано {imported}, обновлено {updated}, пропущено {skipped}, с ошибкой {failed}. Сбои ЭКГ не отбрасывают поддерживаемые записи, импортированные из export.xml.",
"labsResult": "Результаты анализов из медицинских записей: обнаружено {discovered}, импортировано {imported}, уже есть {duplicate}, пропущено {skipped}, с ошибкой {failed}. Сбой одного результата не отбрасывает остальные данные архива.",
"estimateWarning": "Накопительные итоги за {count} день(дней) были оценены по крупнейшему источнику экспорта. Собственная статистика Apple Health остаётся авторитетной.",
"phase": {
"queued": "В очереди…",
@@ -1,7 +1,7 @@
{
"$comment": "Production functions over 200 lines, keyed \"file :: name\", and their length. Maintained by src/__tests__/source-size-ratchet.test.ts.",
"count": 335,
"total": 109021,
"total": 109016,
"entries": {
"app/achievements/page.tsx :: AchievementsPage": 206,
"app/api/admin/backups/upload/route.ts :: apiHandler(arg)": 275,
@@ -192,7 +192,7 @@
"components/settings/coach-nudge-card.tsx :: CoachNudgeCard": 251,
"components/settings/coach-prefs-section.tsx :: CoachPrefsSection": 350,
"components/settings/environment-section.tsx :: EnvironmentSection": 666,
"components/settings/import-panel/apple-health-import-card.tsx :: AppleHealthImportCard": 298,
"components/settings/import-panel/apple-health-import-card.tsx :: AppleHealthImportCard": 293,
"components/settings/import-panel/csv-import-card.tsx :: CsvImportCard": 212,
"components/settings/import-panel/dose-history-import-card.tsx :: DoseHistoryImportCard": 221,
"components/settings/import-panel/health-connect-import-card.tsx :: HealthConnectImportCard": 293,
@@ -47,6 +47,10 @@ const ADMIN_SESSION = {
const NOW = new Date("2026-05-15T10:00:00.000Z");
function ownerSession(): Awaited<ReturnType<typeof getSession>> {
return OWNER_SESSION as unknown as Awaited<ReturnType<typeof getSession>>;
}
function makeRow(overrides: Partial<Record<string, unknown>> = {}) {
return {
id: "ij-1",
@@ -94,7 +98,7 @@ describe("GET /api/import/apple-health-export/[jobId]/status", () => {
});
it("bounds the lab counts and drops anything else in the block", async () => {
vi.mocked(getSession).mockResolvedValue(OWNER_SESSION as never);
vi.mocked(getSession).mockResolvedValue(ownerSession());
mocks.importJobFindUnique.mockResolvedValue(
makeRow({
status: "done",
@@ -127,7 +131,7 @@ describe("GET /api/import/apple-health-export/[jobId]/status", () => {
});
it("reports zeroed lab counts for a job from before labs were read", async () => {
vi.mocked(getSession).mockResolvedValue(OWNER_SESSION as never);
vi.mocked(getSession).mockResolvedValue(ownerSession());
mocks.importJobFindUnique.mockResolvedValue(
makeRow({ status: "done", result: { totals: { recordsRead: 1 } } }),
);
@@ -0,0 +1,61 @@
/**
* The ECG and lab-result lines under a finished Apple Health import.
*/
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { I18nProvider } from "@/lib/i18n/context";
import type { MessageBundle } from "@/lib/i18n/load-locale";
import en from "../../../../../messages/en.json";
import de from "../../../../../messages/de.json";
import { AppleHealthAuxiliaryLines } from "../apple-health-auxiliary-lines";
function render(
props: Parameters<typeof AppleHealthAuxiliaryLines>[0],
locale: "en" | "de" = "en",
): string {
return renderToStaticMarkup(
<I18nProvider
initialLocale={locale}
initialMessages={(locale === "en" ? en : de) as unknown as MessageBundle}
>
<AppleHealthAuxiliaryLines {...props} />
</I18nProvider>,
);
}
describe("<AppleHealthAuxiliaryLines>", () => {
it("renders nothing for an archive with neither", () => {
expect(render({})).toBe("");
expect(render({ ecg: { discovered: 0 }, labs: { discovered: 0 } })).toBe(
"",
);
});
it("renders the lab line with every count", () => {
const html = render({
labs: { discovered: 7, imported: 4, duplicate: 1, skipped: 1, failed: 1 },
});
expect(html).toContain('data-testid="import-apple-health-labs-result"');
expect(html).toContain(
"Lab results from health records: 7 found, 4 imported, 1 already in your record, 1 skipped, 1 failed.",
);
expect(html).not.toContain("import-apple-health-ecg-result");
});
it("renders the ECG line beside it", () => {
const html = render({
ecg: { discovered: 2, imported: 2 },
labs: { discovered: 1, imported: 1 },
});
expect(html).toContain("import-apple-health-ecg-result");
expect(html).toContain("import-apple-health-labs-result");
});
it("speaks the active locale", () => {
expect(render({ labs: { discovered: 2, imported: 2 } }, "de")).toContain(
"Laborwerte aus Gesundheitsakten: 2 gefunden, 2 importiert",
);
});
});
@@ -0,0 +1,66 @@
"use client";
import { useTranslations } from "@/lib/i18n/context";
export interface AppleHealthEcgCounts {
discovered?: number;
imported?: number;
updated?: number;
skipped?: number;
failed?: number;
}
export interface AppleHealthLabCounts {
discovered?: number;
imported?: number;
duplicate?: number;
skipped?: number;
failed?: number;
}
/**
* The outcome lines of the passes that run after export.xml: the ECG
* recordings and the lab results from health records. A line shows only when
* the archive held something of its kind.
*/
export function AppleHealthAuxiliaryLines({
ecg,
labs,
}: {
ecg?: AppleHealthEcgCounts;
labs?: AppleHealthLabCounts;
}) {
const { t } = useTranslations();
return (
<>
{(ecg?.discovered ?? 0) > 0 && (
<p
data-testid="import-apple-health-ecg-result"
className="text-muted-foreground text-xs"
>
{t("settings.sections.export.import.appleHealth.ecgResult", {
discovered: ecg?.discovered ?? 0,
imported: ecg?.imported ?? 0,
updated: ecg?.updated ?? 0,
skipped: ecg?.skipped ?? 0,
failed: ecg?.failed ?? 0,
})}
</p>
)}
{(labs?.discovered ?? 0) > 0 && (
<p
data-testid="import-apple-health-labs-result"
className="text-muted-foreground text-xs"
>
{t("settings.sections.export.import.appleHealth.labsResult", {
discovered: labs?.discovered ?? 0,
imported: labs?.imported ?? 0,
duplicate: labs?.duplicate ?? 0,
skipped: labs?.skipped ?? 0,
failed: labs?.failed ?? 0,
})}
</p>
)}
</>
);
}
@@ -11,6 +11,11 @@ import { queryKeys } from "@/lib/query-keys";
import { useTranslations } from "@/lib/i18n/context";
import { cn } from "@/lib/utils";
import { apiFetchRaw, apiGet } from "@/lib/api/api-fetch";
import {
AppleHealthAuxiliaryLines,
type AppleHealthEcgCounts,
type AppleHealthLabCounts,
} from "./apple-health-auxiliary-lines";
import { ImportCardShell } from "./import-card-shell";
import { WrittenOutcomeLine } from "@/components/outcome/written-outcome-line";
import { classifyWrittenOutcome } from "@/lib/outcome/written-outcome";
@@ -49,13 +54,8 @@ interface JobStatus {
daysFailed?: number;
firstFailureReason?: string | null;
};
ecg?: {
discovered?: number;
imported?: number;
updated?: number;
skipped?: number;
failed?: number;
};
ecg?: AppleHealthEcgCounts;
labs?: AppleHealthLabCounts;
} | null;
failureReason: string | null;
}
@@ -389,7 +389,10 @@ export function AppleHealthImportCard() {
}
})();
const ecg = status?.result?.ecg;
const ecgWritten = (ecg?.imported ?? 0) + (ecg?.updated ?? 0);
const labs = status?.result?.labs;
const rowsWritten = status?.result?.totals?.rowsUpserted ?? 0;
const auxWritten =
(ecg?.imported ?? 0) + (ecg?.updated ?? 0) + (labs?.imported ?? 0);
const skips = summarizeAppleHealthSkips(status?.result ?? null);
const cycleStats = status?.result?.cycle;
@@ -482,18 +485,23 @@ export function AppleHealthImportCard() {
{isDone && (
<WrittenOutcomeLine
outcome={classifyWrittenOutcome({
written: (status?.result?.totals?.rowsUpserted ?? 0) + ecgWritten,
written: rowsWritten + auxWritten,
// Deliberate exclusions (clinical records, unsupported /
// deferred types, a disabled cycle module) are information
// and must not tip the archive into a warning. Genuine
// refusals — samples that SHOULD have landed (unparseable,
// out of range, upsert failure) plus failed cycle days — do.
skipped: skips.refused + (cycleStats?.daysFailed ?? 0),
skipped:
skips.refused +
(cycleStats?.daysFailed ?? 0) +
(labs?.failed ?? 0),
})}
message={
(status?.result?.totals?.rowsUpserted ?? 0) > 0
// An archive whose only new data is lab results or ECGs still
// imported something.
rowsWritten + auxWritten > 0
? t("settings.sections.export.import.appleHealth.doneSummary", {
imported: status?.result?.totals?.rowsUpserted ?? 0,
imported: rowsWritten,
read: status?.result?.totals?.recordsRead ?? 0,
skipped: status?.result?.clinical?.skipped ?? 0,
})
@@ -505,20 +513,7 @@ export function AppleHealthImportCard() {
/>
)}
{isDone && <AppleHealthSkipLines skips={skips} cycle={cycleStats} />}
{isDone && (ecg?.discovered ?? 0) > 0 && (
<p
data-testid="import-apple-health-ecg-result"
className="text-muted-foreground text-xs"
>
{t("settings.sections.export.import.appleHealth.ecgResult", {
discovered: ecg?.discovered ?? 0,
imported: ecg?.imported ?? 0,
updated: ecg?.updated ?? 0,
skipped: ecg?.skipped ?? 0,
failed: ecg?.failed ?? 0,
})}
</p>
)}
{isDone && <AppleHealthAuxiliaryLines ecg={ecg} labs={labs} />}
{isDone && ownRecordsSkipped > 0 && (
<AppleHealthOwnRecordsNote count={ownRecordsSkipped} />
)}