diff --git a/messages/de.json b/messages/de.json index 06ca76108..70beed699 100644 --- a/messages/de.json +++ b/messages/de.json @@ -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…", diff --git a/messages/en.json b/messages/en.json index bc4d11216..1be19e44a 100644 --- a/messages/en.json +++ b/messages/en.json @@ -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…", diff --git a/messages/es.json b/messages/es.json index 41be21086..ac13e1f0a 100644 --- a/messages/es.json +++ b/messages/es.json @@ -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…", diff --git a/messages/fr.json b/messages/fr.json index 84226f8ee..e5ae04a6c 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -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…", diff --git a/messages/it.json b/messages/it.json index 506eb23f8..1166eb957 100644 --- a/messages/it.json +++ b/messages/it.json @@ -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…", diff --git a/messages/ko.json b/messages/ko.json index 89fe1732c..3102f802f 100644 --- a/messages/ko.json +++ b/messages/ko.json @@ -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": "대기 중…", diff --git a/messages/nl.json b/messages/nl.json index ddf85f494..f149d376a 100644 --- a/messages/nl.json +++ b/messages/nl.json @@ -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…", diff --git a/messages/pl.json b/messages/pl.json index aa2b039d2..cca8625d5 100644 --- a/messages/pl.json +++ b/messages/pl.json @@ -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…", diff --git a/messages/pt-BR.json b/messages/pt-BR.json index 351ec8538..c775d0809 100644 --- a/messages/pt-BR.json +++ b/messages/pt-BR.json @@ -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…", diff --git a/messages/ru.json b/messages/ru.json index acd103c36..19d2aa1d3 100644 --- a/messages/ru.json +++ b/messages/ru.json @@ -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": "В очереди…", diff --git a/src/__tests__/baselines/source-function-lines.json b/src/__tests__/baselines/source-function-lines.json index 2b56cc68d..d7f9d5203 100644 --- a/src/__tests__/baselines/source-function-lines.json +++ b/src/__tests__/baselines/source-function-lines.json @@ -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, diff --git a/src/app/api/import/apple-health-export/[jobId]/status/__tests__/route.test.ts b/src/app/api/import/apple-health-export/[jobId]/status/__tests__/route.test.ts index 892758aee..fb251daeb 100644 --- a/src/app/api/import/apple-health-export/[jobId]/status/__tests__/route.test.ts +++ b/src/app/api/import/apple-health-export/[jobId]/status/__tests__/route.test.ts @@ -47,6 +47,10 @@ const ADMIN_SESSION = { const NOW = new Date("2026-05-15T10:00:00.000Z"); +function ownerSession(): Awaited> { + return OWNER_SESSION as unknown as Awaited>; +} + function makeRow(overrides: Partial> = {}) { 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 } } }), ); diff --git a/src/components/settings/import-panel/__tests__/apple-health-auxiliary-lines.test.tsx b/src/components/settings/import-panel/__tests__/apple-health-auxiliary-lines.test.tsx new file mode 100644 index 000000000..603b6f543 --- /dev/null +++ b/src/components/settings/import-panel/__tests__/apple-health-auxiliary-lines.test.tsx @@ -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[0], + locale: "en" | "de" = "en", +): string { + return renderToStaticMarkup( + + + , + ); +} + +describe("", () => { + 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", + ); + }); +}); diff --git a/src/components/settings/import-panel/apple-health-auxiliary-lines.tsx b/src/components/settings/import-panel/apple-health-auxiliary-lines.tsx new file mode 100644 index 000000000..07c758d8a --- /dev/null +++ b/src/components/settings/import-panel/apple-health-auxiliary-lines.tsx @@ -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 && ( +

+ {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, + })} +

+ )} + {(labs?.discovered ?? 0) > 0 && ( +

+ {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, + })} +

+ )} + + ); +} diff --git a/src/components/settings/import-panel/apple-health-import-card.tsx b/src/components/settings/import-panel/apple-health-import-card.tsx index 670100f30..12a8e32ba 100644 --- a/src/components/settings/import-panel/apple-health-import-card.tsx +++ b/src/components/settings/import-panel/apple-health-import-card.tsx @@ -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 && ( 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 && } - {isDone && (ecg?.discovered ?? 0) > 0 && ( -

- {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, - })} -

- )} + {isDone && } {isDone && ownRecordsSkipped > 0 && ( )}