Files
HealthLog/src/lib/validations/health-record-export.ts
T
Marc-André BombeckandClaude Opus 4.8 e984ada5f1 feat(cycle): import Apple Health reproductive data into cycle, add cycle export
Promote the reproductive HealthKit category types out of the
Apple-Health-import privacy-hold list and route them into cycle day-logs
instead of measurements, and surface cycle data on the three export
surfaces.

Import promotion:
- A new HealthKit -> cycle mapping module is the single source of truth for
  how MenstrualFlow, IntermenstrualBleeding, CervicalMucusQuality,
  OvulationTestResult, SexualActivity, PregnancyTestResult,
  ProgesteroneTestResult, Contraceptive and the symptom category types fold
  into CycleDayLog fields / seeded symptom keys. The XML importer
  accumulates same-day reproductive samples and writes one canonical
  day-log per day with source APPLE_HEALTH and a synthetic per-day
  externalId for idempotent re-import. The fold is gated on cycle tracking
  being enabled, so a non-cycle export never provisions cycle rows. A
  contraceptive method nudges the profile goal toward avoiding pregnancy
  only when the goal is still on its default. Basal body temperature stays
  a measurement and mirrors onto the day-log. Pregnancy/Lactation status
  and the pregnancy-bleeding types stay deferred; the cycle awareness types
  remain server-derived.

Export:
- FHIR emits LMP (LOINC 8665-2), average cycle length (64700-8), period
  length (64698-4) and the current phase as opt-in reproductive-health
  observations grouped into their own document section.
- The doctor PDF gains an opt-in cycle section (recent cycles, average
  length and variability, current phase), privacy-default off like mood.
- The full-backup export, the weekly backup worker and the off-host DR
  snapshot include the cycle tables, and the admin restore re-creates them;
  the day-log note round-trips as ciphertext and is never decrypted onto a
  report surface.

Mapping table documented in docs/api/cycle-healthkit-mapping.md. Adds unit
+ integration coverage for the mapping, the import routing, the FHIR
observations and the backup round-trip. OpenAPI regenerated. Six-locale
strings added.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-06 10:16:54 +02:00

140 lines
4.4 KiB
TypeScript

/**
* v1.7.0 — health-record / doctor-handover export selection.
*
* Single strict Zod schema driving `POST /api/export/health-record`. The
* flagship export route fails loudly on bad input (unlike the legacy
* doctor-report route which tolerates drift) — `.strict()` rejects unknown
* keys, and there is intentionally NO `userId` field (the user is always
* narrowed from `requireAuth()`, never accepted from the body).
*
* The grouped `sections` shape is additive over the flat
* `DoctorReportPrefs` used by the aggregator + PDF renderer. The
* `toDoctorReportPrefs()` helper folds the grouped toggles down to the
* flat shape the aggregator consumes, so PDF and FHIR describe identical
* numbers (the source-of-truth property the two PDF endpoints share).
*/
import { z } from "zod/v4";
import { locales } from "@/lib/i18n/config";
import {
DEFAULT_DOCTOR_REPORT_PREFS,
type DoctorReportPrefs,
} from "@/lib/validations/doctor-report-prefs";
/** Grouped vital toggles. */
const vitalsGroupSchema = z
.object({
weight: z.boolean(),
bp: z.boolean(),
pulse: z.boolean(),
oxygenSaturation: z.boolean(),
bodyFat: z.boolean(),
bodyComposition: z.boolean(),
})
.partial();
const cardioFitnessGroupSchema = z
.object({
restingHeartRate: z.boolean(),
hrv: z.boolean(),
vo2max: z.boolean(),
})
.partial();
const activityGroupSchema = z
.object({
steps: z.boolean(),
distance: z.boolean(),
energy: z.boolean(),
sleep: z.boolean(),
})
.partial();
const medicationsGroupSchema = z
.object({
list: z.boolean(),
compliance: z.boolean(),
glp1: z.boolean(),
sideEffects: z.boolean(),
})
.partial();
/**
* Grouped section toggles. Every group + key is optional so a partial
* payload (the user flipped one checkbox) doesn't have to re-state the
* whole tree. Missing keys resolve to the documented defaults.
*/
export const exportSectionsSchema = z
.object({
vitals: vitalsGroupSchema,
cardioFitness: cardioFitnessGroupSchema,
activity: activityGroupSchema,
glucose: z.boolean(),
medications: medicationsGroupSchema,
mood: z.boolean(),
bmi: z.boolean(),
// Cycle / reproductive health — opt-in (privacy default OFF, like mood).
cycle: z.boolean(),
})
.partial();
export type ExportSections = z.infer<typeof exportSectionsSchema>;
/**
* Flagship export selection. `.strict()` so unknown keys (including any
* attempt to smuggle a `userId`) 422 via `returnAllZodIssues`.
*/
export const exportSelectionSchema = z
.object({
format: z.enum(["pdf", "fhir", "package"]),
range: z
.object({
startDate: z.iso.datetime({ offset: true }).optional(),
endDate: z.iso.datetime({ offset: true }).optional(),
days: z.number().int().min(1).max(365).optional(),
})
.strict()
.optional(),
sections: exportSectionsSchema.optional(),
locale: z.enum(locales).optional(),
practiceName: z.string().max(120).optional(),
includeCharts: z.boolean().optional(),
includeAiSummary: z.boolean().optional(),
// FHIR only: additionally emit the German BfArM ATC URI alongside the WHO
// entry on each medication concept (WHO stays first, byte-identical). When
// omitted, the route derives it from a German-region locale.
germanAtc: z.boolean().optional(),
})
.strict();
export type ExportSelection = z.infer<typeof exportSelectionSchema>;
/**
* Fold the grouped selection down to the flat `DoctorReportPrefs` the
* aggregator + PDF renderer consume. A group toggle that is `true` (or
* absent, falling back to the section default) flips the matching flat
* flag. Mood stays privacy-default-OFF: it only flips on when the caller
* explicitly set `sections.mood = true`.
*/
export function toDoctorReportPrefs(
sections: ExportSections | undefined,
): DoctorReportPrefs {
const s = sections ?? {};
const v = s.vitals ?? {};
const a = s.activity ?? {};
const m = s.medications ?? {};
const fallback = DEFAULT_DOCTOR_REPORT_PREFS;
return {
weight: v.weight ?? fallback.weight,
bp: v.bp ?? fallback.bp,
pulse: v.pulse ?? fallback.pulse,
bmi: s.bmi ?? fallback.bmi,
// Mood is opt-in: only true when explicitly requested.
mood: s.mood === true,
compliance: m.compliance ?? m.list ?? fallback.compliance,
sleep: a.sleep ?? fallback.sleep,
// Cycle is opt-in: only true when explicitly requested (privacy).
cycle: s.cycle === true,
};
}