mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-11 05:42:19 +00:00
feat: lay down the day view and timeline contract
Land every file the day view, the timeline and life events share before any of them is built, so the server, the day view and the timeline can be built side by side without editing the same file (#613). Schema and migration 0387: LifeEvent with a short category list, calendar start and end dates, a day/month/year precision, encrypted title and note, a soft-delete tombstone and an index for the per-user live list. Every new column is annotated for the column-reader sweep. Life events travel in both backup purposes with their two ends in one file, are wiped with the account, and are registered for key rotation. src/lib/day/contract.ts carries the constants and wire types for GET /api/day/{date}, /api/day/index, /api/timeline, /api/timeline/readiness and the life-event routes, free of Zod so the navigation chrome can import it; the schemas beside it feed the routes and the published contract. The Coach and MCP tool name get_day is reserved there, and life events are listed as the one section no model ever sees. The opt-in timeline module, its navigation entry, the day-section and timeline-lane surfaces, the day and timeline query keys (evicted by every record data bundle), and stub routes that answer 501 behind their admissions. The four cross-section reads declare the whole record for now; the life-event list is a profile read, and life events join the profile sharing domain and its consent copy in all seven locales. The day, timeline and lifeEvents message namespaces carry their base copy as release-pending keys. The aggregate bundle cap moves to 4400: the branch already measured 4365 against 4335, and the new copy adds 10 KB.
This commit is contained in:
1 parent
861ba21086
commit
c79fc6cc7b
57 files changed
+4290
-21
No files matched your search
@@ -444,6 +444,7 @@ function makePrisma() {
|
||||
// builder must still answer for.
|
||||
ecgRecording: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
symptomDefinition: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
lifeEvent: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
// Left unmocked on purpose: `buildProfileBackupSection` runs for real
|
||||
// against these, so the assertions below exercise the builder rather than
|
||||
// a stand-in that would agree with whatever the payload happened to do.
|
||||
|
||||
@@ -315,6 +315,7 @@ function sourceClient() {
|
||||
extractedFact: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
ecgRecording: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
symptomDefinition: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
lifeEvent: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
customMetric: {
|
||||
findMany: vi.fn().mockResolvedValue([
|
||||
{
|
||||
|
||||
@@ -111,6 +111,9 @@ export const BACKED_UP_MODELS = [
|
||||
// else holds either; a restore without them loses the history outright.
|
||||
"SymptomDefinition",
|
||||
"SymptomEvent",
|
||||
// v1.42 — the person's life events, the timeline's anchors. Written by the
|
||||
// person and held nowhere else.
|
||||
"LifeEvent",
|
||||
"EcgRecording",
|
||||
"UserHealthProfile",
|
||||
"HealthProfileFactRevision",
|
||||
@@ -274,6 +277,8 @@ export const BACKUP_WRITER_FILES: readonly string[] = [
|
||||
// ride inside their definition (`include: { events }` out, `events: {
|
||||
// create }` back), the way a medication's side effects do.
|
||||
"src/lib/export/symptoms-backup.ts",
|
||||
// The person's life events, both ends beside each other (v1.42).
|
||||
"src/lib/export/life-events-backup.ts",
|
||||
"src/lib/cycle/backup.ts",
|
||||
// The medication category is read through the one helper that normalises
|
||||
// it; the payload writer calls the helper rather than the delegate. The
|
||||
@@ -297,6 +302,7 @@ export const BACKUP_RESTORE_FILES: readonly string[] = [
|
||||
"src/lib/export/onboarding-backup.ts",
|
||||
"src/lib/export/ecg-backup.ts",
|
||||
"src/lib/export/symptoms-backup.ts",
|
||||
"src/lib/export/life-events-backup.ts",
|
||||
"src/lib/cycle/backup.ts",
|
||||
// The restore writes the medication category through the same helper.
|
||||
"src/lib/medication-category.ts",
|
||||
@@ -344,6 +350,7 @@ export const TWO_ENDED_MODELS = [
|
||||
"IllnessSymptomLink",
|
||||
"SymptomDefinition",
|
||||
"SymptomEvent",
|
||||
"LifeEvent",
|
||||
"UserHealthProfile",
|
||||
"HealthProfileFactRevision",
|
||||
"CycleProfile",
|
||||
|
||||
@@ -115,6 +115,12 @@ import {
|
||||
type SymptomsBackupCounts,
|
||||
type SymptomsBackupSection,
|
||||
} from "@/lib/export/symptoms-backup";
|
||||
import {
|
||||
buildLifeEventsBackupSection,
|
||||
countLifeEventsBackupSection,
|
||||
type LifeEventsBackupCounts,
|
||||
type LifeEventsBackupSection,
|
||||
} from "@/lib/export/life-events-backup";
|
||||
import {
|
||||
buildIntradayProfileBackupSection,
|
||||
countIntradayProfileBackupSection,
|
||||
@@ -153,7 +159,8 @@ export interface FullBackupCounts
|
||||
EnvironmentBackupCounts,
|
||||
OnboardingBackupCounts,
|
||||
EcgBackupCounts,
|
||||
SymptomsBackupCounts {
|
||||
SymptomsBackupCounts,
|
||||
LifeEventsBackupCounts {
|
||||
measurements: number;
|
||||
medications: number;
|
||||
intakeEvents: number;
|
||||
@@ -724,6 +731,7 @@ export async function buildFullBackupPayload(
|
||||
onboardingRecord,
|
||||
ecg,
|
||||
symptoms,
|
||||
lifeEvents,
|
||||
nutrientDays,
|
||||
accountSettings,
|
||||
] = await Promise.all([
|
||||
@@ -908,6 +916,11 @@ export async function buildFullBackupPayload(
|
||||
buildSymptomsBackupSection(prisma, userId, {
|
||||
purpose: disasterRecovery ? "disaster-recovery" : "portable-export",
|
||||
}),
|
||||
// The person's life events (v1.42). Both ends live in
|
||||
// `src/lib/export/life-events-backup.ts`.
|
||||
buildLifeEventsBackupSection(prisma, userId, {
|
||||
purpose: disasterRecovery ? "disaster-recovery" : "portable-export",
|
||||
}),
|
||||
// Nutrient day totals were absent from every export path, which
|
||||
// contradicted the schema's own reason for denormalising the unit column
|
||||
// ("rows stay self-describing in exports even if the catalog ever drifts").
|
||||
@@ -962,6 +975,7 @@ export async function buildFullBackupPayload(
|
||||
const environmentSection: EnvironmentBackupSection = environment;
|
||||
const ecgSection: EcgBackupSection = ecg;
|
||||
const symptomsSection: SymptomsBackupSection = symptoms;
|
||||
const lifeEventsSection: LifeEventsBackupSection = lifeEvents;
|
||||
const accountSettingsSection: AccountSettingsBackupSection = accountSettings;
|
||||
|
||||
// The three unbounded tables, either read into arrays or left as markers
|
||||
@@ -1363,6 +1377,7 @@ export async function buildFullBackupPayload(
|
||||
...environmentSection,
|
||||
...ecgSection,
|
||||
...symptomsSection,
|
||||
...lifeEventsSection,
|
||||
nutrientDays: nutrientDays.map((n) => ({
|
||||
day: n.day,
|
||||
nutrient: n.nutrient,
|
||||
@@ -1431,6 +1446,7 @@ export async function buildFullBackupPayload(
|
||||
...countEnvironmentBackupSection(environment),
|
||||
...countEcgBackupSection(ecg),
|
||||
...countSymptomsBackupSection(symptoms),
|
||||
...countLifeEventsBackupSection(lifeEvents),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* Life events (v1.42, #613), with both backup ends in one file.
|
||||
*
|
||||
* Same arrangement as `symptoms-backup.ts`: a reader asking "is this carried
|
||||
* at both ends?" answers it here, and a reader who greps only the restore
|
||||
* route gets a false negative because the route delegates.
|
||||
*
|
||||
* ## Free text follows the note contract
|
||||
*
|
||||
* A disaster-recovery payload carries the title and note ciphertext verbatim
|
||||
* as base64, which the same instance's key reads back unchanged, and keeps
|
||||
* the soft-deleted rows with their tombstones so an undo window survives the
|
||||
* round trip. A portable export decrypts both, because a portable file exists
|
||||
* to be readable by the person who owns it and to restore under another
|
||||
* instance's key, and leaves the deleted rows out. A title this instance
|
||||
* cannot decrypt travels as the visible unreadable marker rather than as
|
||||
* nothing, the rule `records-backup.ts` states for notes.
|
||||
*
|
||||
* Nothing references a life event and a life event references nothing but
|
||||
* its owner, so the section restores in any order against the others.
|
||||
*/
|
||||
import { Buffer } from "node:buffer";
|
||||
|
||||
import type { Prisma, PrismaClient } from "@/generated/prisma/client";
|
||||
import type {
|
||||
LifeEventCategory,
|
||||
LifeEventPrecision,
|
||||
} from "@/generated/prisma/client";
|
||||
|
||||
import { decryptFromBytes, encryptToBytes } from "@/lib/ai/coach/bytes-codec";
|
||||
import { getEvent } from "@/lib/logging/context";
|
||||
|
||||
import { UNREADABLE_EXPORT_MARKER } from "./unreadable-marker";
|
||||
|
||||
export interface LifeEventsBackupOptions {
|
||||
purpose?: "portable-export" | "disaster-recovery";
|
||||
}
|
||||
|
||||
/** One life event as the backup carries it. */
|
||||
export interface LifeEventBackupEntry {
|
||||
/** Present in a disaster-recovery payload. */
|
||||
id?: string;
|
||||
category: LifeEventCategory;
|
||||
startDate: string;
|
||||
endDate: string | null;
|
||||
precision: LifeEventPrecision;
|
||||
/** Plaintext; present on a portable payload. */
|
||||
title?: string;
|
||||
/** Ciphertext as base64; present on a disaster-recovery payload. */
|
||||
titleEncrypted?: string;
|
||||
/** Plaintext; present on a portable payload. */
|
||||
note?: string | null;
|
||||
/** Ciphertext as base64; present on a disaster-recovery payload. */
|
||||
noteEncrypted?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
/** Present on a disaster-recovery payload. */
|
||||
deletedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface LifeEventsBackupSection {
|
||||
lifeEvents: LifeEventBackupEntry[];
|
||||
}
|
||||
|
||||
export interface LifeEventsBackupCounts {
|
||||
lifeEvents: number;
|
||||
}
|
||||
|
||||
function base64(buf: Uint8Array): string {
|
||||
return Buffer.from(buf).toString("base64");
|
||||
}
|
||||
|
||||
function readTextForExport(buf: Uint8Array, field: string): string {
|
||||
try {
|
||||
return decryptFromBytes(buf);
|
||||
} catch (err) {
|
||||
getEvent()?.addWarning(
|
||||
`life event ${field} decrypt failed: ${
|
||||
err instanceof Error ? err.message : String(err)
|
||||
}`,
|
||||
);
|
||||
return UNREADABLE_EXPORT_MARKER;
|
||||
}
|
||||
}
|
||||
|
||||
/** Build the life-event slice of a user's full backup. */
|
||||
export async function buildLifeEventsBackupSection(
|
||||
prisma: Pick<PrismaClient, "lifeEvent">,
|
||||
userId: string,
|
||||
options: LifeEventsBackupOptions = {},
|
||||
): Promise<LifeEventsBackupSection> {
|
||||
const disasterRecovery = options.purpose === "disaster-recovery";
|
||||
const rows = await prisma.lifeEvent.findMany({
|
||||
where: disasterRecovery ? { userId } : { userId, deletedAt: null },
|
||||
orderBy: [{ startDate: "asc" }, { createdAt: "asc" }, { id: "asc" }],
|
||||
});
|
||||
|
||||
return {
|
||||
lifeEvents: rows.map((row) => ({
|
||||
...(disasterRecovery
|
||||
? {
|
||||
id: row.id,
|
||||
titleEncrypted: base64(row.titleEncrypted),
|
||||
noteEncrypted: row.noteEncrypted ? base64(row.noteEncrypted) : null,
|
||||
}
|
||||
: {
|
||||
title: readTextForExport(row.titleEncrypted, "title"),
|
||||
note: row.noteEncrypted
|
||||
? readTextForExport(row.noteEncrypted, "note")
|
||||
: null,
|
||||
}),
|
||||
category: row.category,
|
||||
startDate: row.startDate,
|
||||
endDate: row.endDate,
|
||||
precision: row.precision,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
...(disasterRecovery
|
||||
? { deletedAt: row.deletedAt?.toISOString() ?? null }
|
||||
: {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function countLifeEventsBackupSection(
|
||||
section: LifeEventsBackupSection,
|
||||
): LifeEventsBackupCounts {
|
||||
return { lifeEvents: section.lifeEvents.length };
|
||||
}
|
||||
|
||||
/** Counts the life-event restore wiped, for the audit trail. */
|
||||
export interface LifeEventsRestoreCleared {
|
||||
lifeEvents: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the parser hands over, which is looser than what the builder writes:
|
||||
* a file from before v1.42 carries no key at all, and optional columns arrive
|
||||
* as `undefined` rather than `null`.
|
||||
*/
|
||||
export interface LifeEventsRestoreInput {
|
||||
lifeEvents: Array<{
|
||||
id?: string | undefined;
|
||||
category: LifeEventCategory;
|
||||
startDate: string;
|
||||
endDate?: string | null | undefined;
|
||||
precision: LifeEventPrecision;
|
||||
title?: string | undefined;
|
||||
titleEncrypted?: string | undefined;
|
||||
note?: string | null | undefined;
|
||||
noteEncrypted?: string | null | undefined;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
deletedAt?: string | null | undefined;
|
||||
}>;
|
||||
}
|
||||
|
||||
function decodeBytes(encoded: string): Uint8Array<ArrayBuffer> {
|
||||
const decoded = Buffer.from(encoded, "base64");
|
||||
const bytes = new Uint8Array(new ArrayBuffer(decoded.byteLength));
|
||||
bytes.set(decoded);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-create the account's life events. Delete-then-recreate inside the
|
||||
* caller's transaction, like every other section.
|
||||
*/
|
||||
export async function restoreLifeEventsData(
|
||||
tx: Prisma.TransactionClient,
|
||||
ownerId: string,
|
||||
payload: LifeEventsRestoreInput,
|
||||
): Promise<LifeEventsRestoreCleared> {
|
||||
const cleared = await tx.lifeEvent.deleteMany({ where: { userId: ownerId } });
|
||||
|
||||
if (payload.lifeEvents.length > 0) {
|
||||
await tx.lifeEvent.createMany({
|
||||
data: payload.lifeEvents.map((event) => ({
|
||||
...(event.id ? { id: event.id } : {}),
|
||||
userId: ownerId,
|
||||
category: event.category,
|
||||
startDate: event.startDate,
|
||||
endDate: event.endDate ?? null,
|
||||
precision: event.precision,
|
||||
titleEncrypted:
|
||||
event.titleEncrypted !== undefined
|
||||
? decodeBytes(event.titleEncrypted)
|
||||
: encryptToBytes(event.title ?? ""),
|
||||
noteEncrypted:
|
||||
event.noteEncrypted !== undefined
|
||||
? event.noteEncrypted === null
|
||||
? null
|
||||
: decodeBytes(event.noteEncrypted)
|
||||
: event.note
|
||||
? encryptToBytes(event.note)
|
||||
: null,
|
||||
createdAt: new Date(event.createdAt),
|
||||
updatedAt: new Date(event.updatedAt),
|
||||
deletedAt: event.deletedAt ? new Date(event.deletedAt) : null,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
return { lifeEvents: cleared.count };
|
||||
}
|
||||
@@ -114,6 +114,7 @@ import { restoreAwardsData } from "@/lib/export/awards-backup";
|
||||
import { restoreEnvironmentData } from "@/lib/export/environment-backup";
|
||||
import { restoreEcgData } from "@/lib/export/ecg-backup";
|
||||
import { restoreSymptomsData } from "@/lib/export/symptoms-backup";
|
||||
import { restoreLifeEventsData } from "@/lib/export/life-events-backup";
|
||||
import { restoredMedicationCreatedAt } from "@/lib/export/medication-created-at";
|
||||
import {
|
||||
encryptCategoryLabel,
|
||||
@@ -195,6 +196,7 @@ export interface RestoreResponse {
|
||||
environmentTravelLocations: number;
|
||||
ecgRecordings: number;
|
||||
symptomDefinitions: number;
|
||||
lifeEvents: number;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2276,6 +2278,16 @@ export async function restoreBackup(
|
||||
skips,
|
||||
);
|
||||
|
||||
// The person's life events (v1.42). They reference nothing but the
|
||||
// account, so they have no ordering constraint and sit beside the
|
||||
// other person-made rows. Both ends live in
|
||||
// `src/lib/export/life-events-backup.ts`.
|
||||
const lifeEventsCleared = await restoreLifeEventsData(
|
||||
tx,
|
||||
ownerId,
|
||||
payload,
|
||||
);
|
||||
|
||||
reportSection("allergies");
|
||||
for (const allergy of payload.allergies) {
|
||||
await tx.allergy.create({
|
||||
@@ -2663,6 +2675,7 @@ export async function restoreBackup(
|
||||
environmentCleared.environmentTravelLocations,
|
||||
ecgRecordings: ecgCleared.ecgRecordings,
|
||||
symptomDefinitions: symptomsCleared.symptomDefinitions,
|
||||
lifeEvents: lifeEventsCleared.lifeEvents,
|
||||
};
|
||||
assertNoNewForeignReferences(
|
||||
foreignBefore,
|
||||
|
||||
Reference in new issue
Block a user