diff --git a/.env.example b/.env.example
index d0429a85..e8afc941 100644
--- a/.env.example
+++ b/.env.example
@@ -69,3 +69,8 @@ BILLING_ENABLED=false
# REQUIRED, no default: true = Stripe Tax adds tax at checkout, false = list price only.
# STRIPE_AUTOMATIC_TAX=
+
+# P1-B wellness. OFF by default; adult-only for now. Do not enable until
+# Personal P1-A is merged, the migration and privacy acceptance are complete.
+# Native HealthKit and Health Connect are NOT enabled by this flag.
+PERSONAL_WELLNESS_ENABLED=false
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 51759774..1842545a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -259,6 +259,8 @@ jobs:
run: node --test tests/integration/b8-stripe.test.mjs
- name: Validate Personal bio, measurement privacy, consent and erase paths on PG17
run: node --test tests/integration/personal-service.test.mjs
+ - name: Validate P1-B wellness privacy, idempotency, export and erase on PG17
+ run: node --test tests/integration/p1b-wellness.test.mjs
- name: Validate B8 operator billing tools (dry run, grant, revoke, reconcile parity) on PG17
run: |
bash -n infra/billing/clubkeep-billing-ops.sh
diff --git a/docs/P1B_WELLNESS_ENGINE.md b/docs/P1B_WELLNESS_ENGINE.md
new file mode 100644
index 00000000..2283897b
--- /dev/null
+++ b/docs/P1B_WELLNESS_ENGINE.md
@@ -0,0 +1,31 @@
+# Personal P1-B — Wellness Engine
+
+**Status:** stacked implementation PR on top of draft Personal P1-A (#44). Feature disabled by default. Native integrations and medical features are NOT shipped.
+
+## Scope
+- User-owned active/archived goals, completed workout log (with structured exercise/sets), manual sleep, meals, hydration and optional recovery journal.
+- Private 90-day descriptive insights and goal progress based on completed records. No AI-generated score, diagnosis, emergency monitoring, or inferred nutrient values.
+- Limited completed-workout form: one optional strength exercise/set per submission, no running/pause/offline-draft engine in this PR. Broader exercise editor is follow-up.
+- No provider credentials, HealthKit, Health Connect, medical-history tables, medications, BP, glucose or insurer/ABHA routes.
+- `PERSONAL_WELLNESS_ENABLED=false` until adult policy, privacy, stage and backup/restore acceptance. The flag protects all new writes, reads and routes; existing P1-A remains separately accessible.
+
+## Ownership and privacy
+- Authenticated, verified-email Better Auth session required; POST same-origin and fail-closed Redis guards inherited from Personal P1-A; adult rule is conservative birth-year threshold 19 until jurisdiction-aware DOB/guardian policy exists.
+- All wellness rows bind directly to global user ID and never to Club tenancy. Club attendance may affect a Personal-only muscle estimate solely under existing consent; there is **no reverse health-to-club access**.
+- Workout, sleep, meal and water writes use per-user UUID idempotency keys. Source metadata is reserved for a future native adapter and not used to authorize any import.
+- Personal export/erase includes new rows and their children, leaving the login and club memberships intact. Retention/backups must follow separately reviewed privacy policy. The existing P1-A measurement-count guard is unchanged, and the owner must reconcile it with Free unlimited essential fitness history.
+
+## Rollout gate
+1. Merge PR #44 and reconcile branch onto the reviewed main; recheck current HM2 login, billing and Personal API changes before merging this PR.
+2. Native PG17 fresh/upgrade/redeploy and restore drill; ensure MenuMinute and ERP unaffected. Never roll back additive schema with drop tables.
+3. x64 and ARM64 CI green, 360/390/768/1440px light/dark responsive browser QA, manual time-zone and cross-user QA.
+4. Confirm legal/age handling by target country; this gate deliberately keeps under-age accounts out.
+5. Set flag only in protected ClubKeep web environment and restart only ClubKeep. Verify api rejection with flag off, and permissions after flag on.
+6. Roll back by setting flag false and restarting ClubKeep; do not delete user records.
+
+## Known limits
+- Goals are weekly/total; for long periods timezone boundary queries may need a stronger zone-aware indexed aggregation model.
+- Recent-days analytics reads capped to avoid an unbounded query; current explicit 90-day view, with total goal progress separately queried.
+- No Personal billing entitlement engine exists yet; essential tracking is free, with advanced Pro analytics deferred rather than granting unapproved access.
+- Recovery is self-reported only. Food macros are optional user-supplied numbers, never inferred.
+- Native HealthKit/Health Connect permissions, per-provider cursors, offline encrypted queue and writeback are separate PRs P1-C/P1-D.
diff --git a/prisma/migrations/20261118190000_p1b_wellness_engine/migration.sql b/prisma/migrations/20261118190000_p1b_wellness_engine/migration.sql
new file mode 100644
index 00000000..7fd0afa9
--- /dev/null
+++ b/prisma/migrations/20261118190000_p1b_wellness_engine/migration.sql
@@ -0,0 +1,116 @@
+-- P1-B private wellness: additive, isolated from club tenancy and medical-history tables.
+CREATE TYPE "WellnessGoalMetric" AS ENUM ('WORKOUT_SESSIONS','ACTIVITY_MINUTES','SLEEP_MINUTES','HYDRATION_ML');
+CREATE TYPE "WellnessGoalCadence" AS ENUM ('WEEKLY','TOTAL');
+CREATE TYPE "WellnessGoalStatus" AS ENUM ('ACTIVE','PAUSED','ARCHIVED');
+CREATE TYPE "WellnessSource" AS ENUM ('MANUAL','HEALTHKIT','HEALTH_CONNECT');
+CREATE TYPE "WellnessMealType" AS ENUM ('BREAKFAST','LUNCH','DINNER','SNACK');
+
+CREATE TABLE "PersonalGoalInstance" (
+ "id" TEXT PRIMARY KEY, "userId" TEXT NOT NULL, "title" VARCHAR(80) NOT NULL,
+ "metric" "WellnessGoalMetric" NOT NULL, "cadence" "WellnessGoalCadence" NOT NULL DEFAULT 'WEEKLY',
+ "target" INTEGER NOT NULL, "status" "WellnessGoalStatus" NOT NULL DEFAULT 'ACTIVE',
+ "startsAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "endsAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL,
+ CONSTRAINT "PersonalGoalInstance_target_check" CHECK ("target" BETWEEN 1 AND 10000000),
+ CONSTRAINT "PersonalGoalInstance_dates_check" CHECK ("endsAt" IS NULL OR "endsAt" > "startsAt"),
+ FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE INDEX "PersonalGoalInstance_userId_status_startsAt_idx" ON "PersonalGoalInstance"("userId","status","startsAt");
+
+CREATE TABLE "WorkoutSession" (
+ "id" TEXT PRIMARY KEY, "userId" TEXT NOT NULL, "requestId" VARCHAR(80) NOT NULL,
+ "title" VARCHAR(100) NOT NULL, "activityKey" VARCHAR(40) NOT NULL,
+ "startedAt" TIMESTAMP(3) NOT NULL, "endedAt" TIMESTAMP(3) NOT NULL,
+ "durationMinutes" INTEGER NOT NULL, "distanceMeters" INTEGER,
+ "notes" VARCHAR(500), "source" "WellnessSource" NOT NULL DEFAULT 'MANUAL',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL,
+ CONSTRAINT "WorkoutSession_duration_check" CHECK ("durationMinutes" BETWEEN 1 AND 1440),
+ CONSTRAINT "WorkoutSession_distance_check" CHECK ("distanceMeters" IS NULL OR "distanceMeters" BETWEEN 0 AND 1000000),
+ CONSTRAINT "WorkoutSession_dates_check" CHECK ("endedAt" > "startedAt"),
+ FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE UNIQUE INDEX "WorkoutSession_userId_requestId_key" ON "WorkoutSession"("userId","requestId");
+CREATE INDEX "WorkoutSession_userId_endedAt_idx" ON "WorkoutSession"("userId","endedAt");
+
+CREATE TABLE "WorkoutExercise" (
+ "id" TEXT PRIMARY KEY, "workoutId" TEXT NOT NULL, "name" VARCHAR(100) NOT NULL,
+ "position" INTEGER NOT NULL, FOREIGN KEY ("workoutId") REFERENCES "WorkoutSession"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE INDEX "WorkoutExercise_workoutId_position_idx" ON "WorkoutExercise"("workoutId","position");
+CREATE TABLE "WorkoutSet" (
+ "id" TEXT PRIMARY KEY, "exerciseId" TEXT NOT NULL, "position" INTEGER NOT NULL,
+ "reps" INTEGER, "weightGrams" INTEGER, "durationSeconds" INTEGER, "distanceMeters" INTEGER,
+ CONSTRAINT "WorkoutSet_reps_check" CHECK ("reps" IS NULL OR "reps" BETWEEN 0 AND 1000),
+ CONSTRAINT "WorkoutSet_weight_check" CHECK ("weightGrams" IS NULL OR "weightGrams" BETWEEN 0 AND 1000000),
+ CONSTRAINT "WorkoutSet_seconds_check" CHECK ("durationSeconds" IS NULL OR "durationSeconds" BETWEEN 0 AND 86400),
+ CONSTRAINT "WorkoutSet_distance_check" CHECK ("distanceMeters" IS NULL OR "distanceMeters" BETWEEN 0 AND 1000000),
+ FOREIGN KEY ("exerciseId") REFERENCES "WorkoutExercise"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE INDEX "WorkoutSet_exerciseId_position_idx" ON "WorkoutSet"("exerciseId","position");
+
+CREATE TABLE "SleepSession" (
+ "id" TEXT PRIMARY KEY, "userId" TEXT NOT NULL, "requestId" VARCHAR(80) NOT NULL,
+ "startedAt" TIMESTAMP(3) NOT NULL, "endedAt" TIMESTAMP(3) NOT NULL, "quality" INTEGER,
+ "isNap" BOOLEAN NOT NULL DEFAULT FALSE, "source" "WellnessSource" NOT NULL DEFAULT 'MANUAL',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL,
+ CONSTRAINT "SleepSession_dates_check" CHECK ("endedAt" > "startedAt" AND "endedAt" < "startedAt" + INTERVAL '24 hours'),
+ CONSTRAINT "SleepSession_quality_check" CHECK ("quality" IS NULL OR "quality" BETWEEN 1 AND 5),
+ FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE UNIQUE INDEX "SleepSession_userId_requestId_key" ON "SleepSession"("userId","requestId");
+CREATE INDEX "SleepSession_userId_endedAt_idx" ON "SleepSession"("userId","endedAt");
+
+CREATE TABLE "MealEntry" (
+ "id" TEXT PRIMARY KEY, "userId" TEXT NOT NULL, "requestId" VARCHAR(80) NOT NULL,
+ "mealType" "WellnessMealType" NOT NULL, "eatenAt" TIMESTAMP(3) NOT NULL, "notes" VARCHAR(300),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL,
+ FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE UNIQUE INDEX "MealEntry_userId_requestId_key" ON "MealEntry"("userId","requestId");
+CREATE INDEX "MealEntry_userId_eatenAt_idx" ON "MealEntry"("userId","eatenAt");
+CREATE TABLE "MealItem" (
+ "id" TEXT PRIMARY KEY, "mealId" TEXT NOT NULL, "name" VARCHAR(100) NOT NULL,
+ "portionGrams" INTEGER, "caloriesKcal" INTEGER, "proteinGrams" INTEGER,
+ "carbsGrams" INTEGER, "fatGrams" INTEGER, "position" INTEGER NOT NULL,
+ CONSTRAINT "MealItem_portion_check" CHECK ("portionGrams" IS NULL OR "portionGrams" BETWEEN 1 AND 50000),
+ CONSTRAINT "MealItem_energy_check" CHECK ("caloriesKcal" IS NULL OR "caloriesKcal" BETWEEN 0 AND 50000),
+ CONSTRAINT "MealItem_protein_check" CHECK ("proteinGrams" IS NULL OR "proteinGrams" BETWEEN 0 AND 10000),
+ CONSTRAINT "MealItem_carbs_check" CHECK ("carbsGrams" IS NULL OR "carbsGrams" BETWEEN 0 AND 10000),
+ CONSTRAINT "MealItem_fat_check" CHECK ("fatGrams" IS NULL OR "fatGrams" BETWEEN 0 AND 10000),
+ FOREIGN KEY ("mealId") REFERENCES "MealEntry"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE INDEX "MealItem_mealId_position_idx" ON "MealItem"("mealId","position");
+
+CREATE TABLE "HydrationEntry" (
+ "id" TEXT PRIMARY KEY, "userId" TEXT NOT NULL, "requestId" VARCHAR(80) NOT NULL,
+ "volumeMl" INTEGER NOT NULL, "takenAt" TIMESTAMP(3) NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ CONSTRAINT "HydrationEntry_volume_check" CHECK ("volumeMl" BETWEEN 1 AND 5000),
+ FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE UNIQUE INDEX "HydrationEntry_userId_requestId_key" ON "HydrationEntry"("userId","requestId");
+CREATE INDEX "HydrationEntry_userId_takenAt_idx" ON "HydrationEntry"("userId","takenAt");
+
+CREATE TABLE "RecoveryCheckIn" (
+ "id" TEXT PRIMARY KEY, "userId" TEXT NOT NULL, "localDate" VARCHAR(10) NOT NULL,
+ "energy" INTEGER, "soreness" INTEGER, "stress" INTEGER, "satisfaction" INTEGER,
+ "notes" VARCHAR(300), "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+ CONSTRAINT "RecoveryCheckIn_ratings_check" CHECK (
+ ("energy" IS NULL OR "energy" BETWEEN 1 AND 5) AND
+ ("soreness" IS NULL OR "soreness" BETWEEN 1 AND 5) AND
+ ("stress" IS NULL OR "stress" BETWEEN 1 AND 5) AND
+ ("satisfaction" IS NULL OR "satisfaction" BETWEEN 1 AND 5)),
+ FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE UNIQUE INDEX "RecoveryCheckIn_userId_localDate_key" ON "RecoveryCheckIn"("userId","localDate");
+
+CREATE TABLE "WellnessSourceRecord" (
+ "id" TEXT PRIMARY KEY, "userId" TEXT NOT NULL, "provider" VARCHAR(40) NOT NULL,
+ "externalId" VARCHAR(200) NOT NULL, "recordType" VARCHAR(40) NOT NULL,
+ "sourceUpdatedAt" TIMESTAMP(3), "deletedAt" TIMESTAMP(3),
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, "updatedAt" TIMESTAMP(3) NOT NULL,
+ FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+CREATE UNIQUE INDEX "WellnessSourceRecord_userId_provider_recordType_externalId_key" ON "WellnessSourceRecord"("userId","provider","recordType","externalId");
+CREATE INDEX "WellnessSourceRecord_userId_provider_idx" ON "WellnessSourceRecord"("userId","provider");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index f8e74444..b3c15e67 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -35,6 +35,13 @@ model User {
personalMeasurements PersonalMeasurement[]
personalActivities PersonalActivity[]
personalClubSignals PersonalClubSignalConsent[]
+ wellnessGoals PersonalGoalInstance[]
+ wellnessWorkouts WorkoutSession[]
+ wellnessSleep SleepSession[]
+ wellnessMeals MealEntry[]
+ wellnessHydration HydrationEntry[]
+ wellnessRecovery RecoveryCheckIn[]
+ wellnessSources WellnessSourceRecord[]
clubMemberships ClubMembership[]
issuedInvites ClubInvite[] @relation("InviteIssuer")
claimedInvites ClubInvite[] @relation("InviteClaimant")
@@ -208,6 +215,181 @@ model PersonalClubSignalConsent {
@@id([userId, clubId])
}
+
+// Wellness records are owned by the global identity, never a club or its staff.
+// P1-B is adult-only until the regional guardian/teen policy is approved.
+enum WellnessGoalMetric {
+ WORKOUT_SESSIONS
+ ACTIVITY_MINUTES
+ SLEEP_MINUTES
+ HYDRATION_ML
+}
+enum WellnessGoalCadence {
+ WEEKLY
+ TOTAL
+}
+enum WellnessGoalStatus {
+ ACTIVE
+ PAUSED
+ ARCHIVED
+}
+enum WellnessSource {
+ MANUAL
+ HEALTHKIT
+ HEALTH_CONNECT
+}
+enum WellnessMealType {
+ BREAKFAST
+ LUNCH
+ DINNER
+ SNACK
+}
+
+model PersonalGoalInstance {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ title String @db.VarChar(80)
+ metric WellnessGoalMetric
+ cadence WellnessGoalCadence @default(WEEKLY)
+ target Int
+ status WellnessGoalStatus @default(ACTIVE)
+ startsAt DateTime @default(now())
+ endsAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ @@index([userId, status, startsAt])
+}
+
+model WorkoutSession {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ requestId String @db.VarChar(80)
+ title String @db.VarChar(100)
+ activityKey String @db.VarChar(40)
+ startedAt DateTime
+ endedAt DateTime
+ durationMinutes Int
+ distanceMeters Int?
+ notes String? @db.VarChar(500)
+ source WellnessSource @default(MANUAL)
+ exercises WorkoutExercise[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ @@unique([userId, requestId])
+ @@index([userId, endedAt])
+}
+
+model WorkoutExercise {
+ id String @id @default(cuid())
+ workoutId String
+ workout WorkoutSession @relation(fields: [workoutId], references: [id], onDelete: Cascade)
+ name String @db.VarChar(100)
+ position Int
+ sets WorkoutSet[]
+ @@index([workoutId, position])
+}
+
+model WorkoutSet {
+ id String @id @default(cuid())
+ exerciseId String
+ exercise WorkoutExercise @relation(fields: [exerciseId], references: [id], onDelete: Cascade)
+ position Int
+ reps Int?
+ weightGrams Int?
+ durationSeconds Int?
+ distanceMeters Int?
+ @@index([exerciseId, position])
+}
+
+model SleepSession {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ requestId String @db.VarChar(80)
+ startedAt DateTime
+ endedAt DateTime
+ quality Int?
+ isNap Boolean @default(false)
+ source WellnessSource @default(MANUAL)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ @@unique([userId, requestId])
+ @@index([userId, endedAt])
+}
+
+model MealEntry {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ requestId String @db.VarChar(80)
+ mealType WellnessMealType
+ eatenAt DateTime
+ notes String? @db.VarChar(300)
+ items MealItem[]
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ @@unique([userId, requestId])
+ @@index([userId, eatenAt])
+}
+
+model MealItem {
+ id String @id @default(cuid())
+ mealId String
+ meal MealEntry @relation(fields: [mealId], references: [id], onDelete: Cascade)
+ name String @db.VarChar(100)
+ portionGrams Int?
+ caloriesKcal Int?
+ proteinGrams Int?
+ carbsGrams Int?
+ fatGrams Int?
+ position Int
+ @@index([mealId, position])
+}
+
+model HydrationEntry {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ requestId String @db.VarChar(80)
+ volumeMl Int
+ takenAt DateTime
+ createdAt DateTime @default(now())
+ @@unique([userId, requestId])
+ @@index([userId, takenAt])
+}
+
+model RecoveryCheckIn {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ localDate String @db.VarChar(10)
+ energy Int?
+ soreness Int?
+ stress Int?
+ satisfaction Int?
+ notes String? @db.VarChar(300)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ @@unique([userId, localDate])
+}
+
+model WellnessSourceRecord {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ provider String @db.VarChar(40)
+ externalId String @db.VarChar(200)
+ recordType String @db.VarChar(40)
+ sourceUpdatedAt DateTime?
+ deletedAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ @@unique([userId, provider, recordType, externalId])
+ @@index([userId, provider])
+}
+
enum PlatformRole {
USER
PLATFORM_ADMIN
diff --git a/src/app/api/me/wellness/goals/change/route.ts b/src/app/api/me/wellness/goals/change/route.ts
new file mode 100644
index 00000000..f74f481a
--- /dev/null
+++ b/src/app/api/me/wellness/goals/change/route.ts
@@ -0,0 +1,10 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost } from "@/lib/personal/wellness-http";
+import { changeGoal } from "@/lib/personal/wellness-goals";
+import { goalChangeInput } from "@/lib/validations/wellness";
+
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "goals-change", 60, goalChangeInput, (db, userId, input) =>
+ changeGoal(db, userId, input)
+ );
+}
diff --git a/src/app/api/me/wellness/goals/remove/route.ts b/src/app/api/me/wellness/goals/remove/route.ts
new file mode 100644
index 00000000..b952b246
--- /dev/null
+++ b/src/app/api/me/wellness/goals/remove/route.ts
@@ -0,0 +1,10 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost } from "@/lib/personal/wellness-http";
+import { removeGoal } from "@/lib/personal/wellness-goals";
+import { wellnessRemoveInput } from "@/lib/validations/wellness";
+
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "goals-remove", 30, wellnessRemoveInput, (db, userId, input) =>
+ removeGoal(db, userId, input.id)
+ );
+}
diff --git a/src/app/api/me/wellness/goals/route.ts b/src/app/api/me/wellness/goals/route.ts
new file mode 100644
index 00000000..1b689e01
--- /dev/null
+++ b/src/app/api/me/wellness/goals/route.ts
@@ -0,0 +1,13 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost, wellnessRead } from "@/lib/personal/wellness-http";
+import { createGoal, listGoals } from "@/lib/personal/wellness-goals";
+import { goalInput } from "@/lib/validations/wellness";
+
+export async function GET(request: NextRequest) {
+ return wellnessRead(request, (db, userId) => listGoals(db, userId));
+}
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "goals-create", 30, goalInput, (db, userId, input) =>
+ createGoal(db, userId, input)
+ );
+}
diff --git a/src/app/api/me/wellness/hydration/remove/route.ts b/src/app/api/me/wellness/hydration/remove/route.ts
new file mode 100644
index 00000000..9dc09679
--- /dev/null
+++ b/src/app/api/me/wellness/hydration/remove/route.ts
@@ -0,0 +1,9 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost } from "@/lib/personal/wellness-http";
+import { removeHydration } from "@/lib/personal/wellness-nutrition";
+import { wellnessRemoveInput } from "@/lib/validations/wellness";
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "hydration-remove", 60, wellnessRemoveInput, (db, userId, input) =>
+ removeHydration(db, userId, input.id)
+ );
+}
diff --git a/src/app/api/me/wellness/hydration/route.ts b/src/app/api/me/wellness/hydration/route.ts
new file mode 100644
index 00000000..f35756bb
--- /dev/null
+++ b/src/app/api/me/wellness/hydration/route.ts
@@ -0,0 +1,12 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost, wellnessRead } from "@/lib/personal/wellness-http";
+import { listNutrition, recordHydration } from "@/lib/personal/wellness-nutrition";
+import { hydrationInput } from "@/lib/validations/wellness";
+export async function GET(request: NextRequest) {
+ return wellnessRead(request, (db, userId) => listNutrition(db, userId).then((x) => x.hydration));
+}
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "hydration-create", 120, hydrationInput, (db, userId, input) =>
+ recordHydration(db, userId, input)
+ );
+}
diff --git a/src/app/api/me/wellness/insights/route.ts b/src/app/api/me/wellness/insights/route.ts
new file mode 100644
index 00000000..28b60000
--- /dev/null
+++ b/src/app/api/me/wellness/insights/route.ts
@@ -0,0 +1,6 @@
+import type { NextRequest } from "next/server";
+import { wellnessRead } from "@/lib/personal/wellness-http";
+import { wellnessInsights } from "@/lib/personal/wellness-insights";
+export async function GET(request: NextRequest) {
+ return wellnessRead(request, (db, userId) => wellnessInsights(db, userId));
+}
diff --git a/src/app/api/me/wellness/meals/remove/route.ts b/src/app/api/me/wellness/meals/remove/route.ts
new file mode 100644
index 00000000..f1f79a08
--- /dev/null
+++ b/src/app/api/me/wellness/meals/remove/route.ts
@@ -0,0 +1,9 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost } from "@/lib/personal/wellness-http";
+import { removeMeal } from "@/lib/personal/wellness-nutrition";
+import { wellnessRemoveInput } from "@/lib/validations/wellness";
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "meals-remove", 60, wellnessRemoveInput, (db, userId, input) =>
+ removeMeal(db, userId, input.id)
+ );
+}
diff --git a/src/app/api/me/wellness/meals/route.ts b/src/app/api/me/wellness/meals/route.ts
new file mode 100644
index 00000000..75ca4756
--- /dev/null
+++ b/src/app/api/me/wellness/meals/route.ts
@@ -0,0 +1,12 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost, wellnessRead } from "@/lib/personal/wellness-http";
+import { listNutrition, recordMeal } from "@/lib/personal/wellness-nutrition";
+import { mealInput } from "@/lib/validations/wellness";
+export async function GET(request: NextRequest) {
+ return wellnessRead(request, (db, userId) => listNutrition(db, userId).then((x) => x.meals));
+}
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "meals-create", 90, mealInput, (db, userId, input) =>
+ recordMeal(db, userId, input)
+ );
+}
diff --git a/src/app/api/me/wellness/recovery/remove/route.ts b/src/app/api/me/wellness/recovery/remove/route.ts
new file mode 100644
index 00000000..03cda734
--- /dev/null
+++ b/src/app/api/me/wellness/recovery/remove/route.ts
@@ -0,0 +1,9 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost } from "@/lib/personal/wellness-http";
+import { removeRecovery } from "@/lib/personal/wellness-recovery";
+import { wellnessRemoveInput } from "@/lib/validations/wellness";
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "recovery-remove", 30, wellnessRemoveInput, (db, userId, input) =>
+ removeRecovery(db, userId, input.id)
+ );
+}
diff --git a/src/app/api/me/wellness/recovery/route.ts b/src/app/api/me/wellness/recovery/route.ts
new file mode 100644
index 00000000..21e60cd3
--- /dev/null
+++ b/src/app/api/me/wellness/recovery/route.ts
@@ -0,0 +1,12 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost, wellnessRead } from "@/lib/personal/wellness-http";
+import { listRecovery, saveRecovery } from "@/lib/personal/wellness-recovery";
+import { recoveryInput } from "@/lib/validations/wellness";
+export async function GET(request: NextRequest) {
+ return wellnessRead(request, (db, userId) => listRecovery(db, userId));
+}
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "recovery-save", 60, recoveryInput, (db, userId, input) =>
+ saveRecovery(db, userId, input)
+ );
+}
diff --git a/src/app/api/me/wellness/sleep/remove/route.ts b/src/app/api/me/wellness/sleep/remove/route.ts
new file mode 100644
index 00000000..52e36545
--- /dev/null
+++ b/src/app/api/me/wellness/sleep/remove/route.ts
@@ -0,0 +1,9 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost } from "@/lib/personal/wellness-http";
+import { removeSleep } from "@/lib/personal/wellness-sleep";
+import { wellnessRemoveInput } from "@/lib/validations/wellness";
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "sleep-remove", 30, wellnessRemoveInput, (db, userId, input) =>
+ removeSleep(db, userId, input.id)
+ );
+}
diff --git a/src/app/api/me/wellness/sleep/route.ts b/src/app/api/me/wellness/sleep/route.ts
new file mode 100644
index 00000000..34dd5153
--- /dev/null
+++ b/src/app/api/me/wellness/sleep/route.ts
@@ -0,0 +1,12 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost, wellnessRead } from "@/lib/personal/wellness-http";
+import { listSleep, recordSleep } from "@/lib/personal/wellness-sleep";
+import { sleepInput } from "@/lib/validations/wellness";
+export async function GET(request: NextRequest) {
+ return wellnessRead(request, (db, userId) => listSleep(db, userId));
+}
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "sleep-create", 60, sleepInput, (db, userId, input) =>
+ recordSleep(db, userId, input)
+ );
+}
diff --git a/src/app/api/me/wellness/workouts/remove/route.ts b/src/app/api/me/wellness/workouts/remove/route.ts
new file mode 100644
index 00000000..e809b0c8
--- /dev/null
+++ b/src/app/api/me/wellness/workouts/remove/route.ts
@@ -0,0 +1,9 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost } from "@/lib/personal/wellness-http";
+import { removeWorkout } from "@/lib/personal/wellness-workouts";
+import { wellnessRemoveInput } from "@/lib/validations/wellness";
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "workouts-remove", 60, wellnessRemoveInput, (db, userId, input) =>
+ removeWorkout(db, userId, input.id)
+ );
+}
diff --git a/src/app/api/me/wellness/workouts/route.ts b/src/app/api/me/wellness/workouts/route.ts
new file mode 100644
index 00000000..084793dc
--- /dev/null
+++ b/src/app/api/me/wellness/workouts/route.ts
@@ -0,0 +1,13 @@
+import type { NextRequest } from "next/server";
+import { wellnessPost, wellnessRead } from "@/lib/personal/wellness-http";
+import { createWorkout, listWorkouts } from "@/lib/personal/wellness-workouts";
+import { workoutInput } from "@/lib/validations/wellness";
+
+export async function GET(request: NextRequest) {
+ return wellnessRead(request, (db, userId) => listWorkouts(db, userId));
+}
+export async function POST(request: NextRequest) {
+ return wellnessPost(request, "workouts-create", 120, workoutInput, (db, userId, input) =>
+ createWorkout(db, userId, input)
+ );
+}
diff --git a/src/app/me/goals/loading.tsx b/src/app/me/goals/loading.tsx
new file mode 100644
index 00000000..379b4f83
--- /dev/null
+++ b/src/app/me/goals/loading.tsx
@@ -0,0 +1,7 @@
+export default function Loading() {
+ return (
+
+ Loading goals…
+
+ );
+}
diff --git a/src/app/me/goals/page.tsx b/src/app/me/goals/page.tsx
new file mode 100644
index 00000000..14b46b45
--- /dev/null
+++ b/src/app/me/goals/page.tsx
@@ -0,0 +1,38 @@
+import { prisma } from "@/lib/prisma";
+import { requireWellnessPage } from "@/lib/personal/wellness-page";
+import { listGoals } from "@/lib/personal/wellness-goals";
+import { GoalForm, GoalActions } from "@/components/personal/wellness-goals";
+
+export default async function GoalsPage() {
+ const userId = await requireWellnessPage();
+ const goals = await listGoals(prisma, userId);
+ return (
+ <>
+
+ A direction to grow
+ My goals
+
+
+
+ My goals
+ {goals.length === 0 ? (
+ You have not added a goal yet.
+ ) : (
+ goals.map((goal) => (
+
+
+ {goal.title}
+ {goal.status.toLowerCase()}
+
+
+ {goal.target.toLocaleString()} {goal.metric.toLowerCase().replaceAll("_", " ")} ·{" "}
+ {goal.cadence.toLowerCase()}
+
+ {goal.status !== "ARCHIVED" && }
+
+ ))
+ )}
+
+ >
+ );
+}
diff --git a/src/app/me/insights/loading.tsx b/src/app/me/insights/loading.tsx
new file mode 100644
index 00000000..429fa0a8
--- /dev/null
+++ b/src/app/me/insights/loading.tsx
@@ -0,0 +1,7 @@
+export default function Loading() {
+ return (
+
+ Loading insights…
+
+ );
+}
diff --git a/src/app/me/insights/page.tsx b/src/app/me/insights/page.tsx
new file mode 100644
index 00000000..5c47d9ff
--- /dev/null
+++ b/src/app/me/insights/page.tsx
@@ -0,0 +1,11 @@
+import { requireWellnessPage } from "@/lib/personal/wellness-page";
+import { WellnessInsightsSection } from "@/components/personal/wellness-insights";
+export default async function InsightsPage() {
+ const userId = await requireWellnessPage();
+ return (
+ <>
+ Wellness insights
+
+ >
+ );
+}
diff --git a/src/app/me/nutrition/loading.tsx b/src/app/me/nutrition/loading.tsx
new file mode 100644
index 00000000..890ec129
--- /dev/null
+++ b/src/app/me/nutrition/loading.tsx
@@ -0,0 +1,7 @@
+export default function Loading() {
+ return (
+
+ Loading nutrition…
+
+ );
+}
diff --git a/src/app/me/nutrition/page.tsx b/src/app/me/nutrition/page.tsx
new file mode 100644
index 00000000..07616f85
--- /dev/null
+++ b/src/app/me/nutrition/page.tsx
@@ -0,0 +1,61 @@
+import { prisma } from "@/lib/prisma";
+import { requireWellnessPage } from "@/lib/personal/wellness-page";
+import { listNutrition } from "@/lib/personal/wellness-nutrition";
+import { MealForm, HydrationForm, RemoveNutrition } from "@/components/personal/wellness-nutrition";
+
+export default async function NutritionPage() {
+ const userId = await requireWellnessPage();
+ const { meals, hydration } = await listNutrition(prisma, userId);
+ return (
+ <>
+
+ Nourishment
+ Nutrition
+
+
+
+
+ Recent meals
+ {meals.length === 0 ? (
+ Start with a simple meal entry.
+ ) : (
+ meals.slice(0, 15).map((m) => (
+
+
+ {m.mealType.toLowerCase()}
+ {m.eatenAt.toLocaleDateString()}
+
+
+ {m.items.map((item) => (
+ -
+ {item.name}
+ {item.portionGrams === null ? "" : " · " + item.portionGrams + " g"}
+ {item.caloriesKcal === null
+ ? ""
+ : " · " + item.caloriesKcal + " kcal (entered)"}
+
+ ))}
+
+
+
+ ))
+ )}
+
+
+ Recent water entries
+ {hydration.length === 0 ? (
+ No water entries yet.
+ ) : (
+ hydration.slice(0, 10).map((w) => (
+
+
+ {w.volumeMl} mL · {w.takenAt.toLocaleString()}
+
+
+
+ ))
+ )}
+
+ >
+ );
+}
diff --git a/src/app/me/page.tsx b/src/app/me/page.tsx
index 499f38e7..a1dcb57c 100644
--- a/src/app/me/page.tsx
+++ b/src/app/me/page.tsx
@@ -5,6 +5,7 @@ import { prisma } from "@/lib/prisma";
import { requireSession } from "@/lib/required-session";
import { getOverview } from "@/lib/personal/personal-service";
import { muscleLabel, type MuscleId } from "@/lib/personal/muscle-map";
+import { WellnessInsightsSection } from "@/components/personal/wellness-insights";
export default async function TodayPage() {
const session = await requireSession();
@@ -16,6 +17,7 @@ export default async function TodayPage() {
.slice(0, 3);
const clubVisits = o.clubs.reduce((n, c) => n + (c.visits28d ?? 0), 0);
const logged = Object.values(o.measurements).reduce((n, list) => n + list.length, 0);
+ const wellnessReady = process.env.PERSONAL_WELLNESS_ENABLED === "true" && o.canLogMeasurements;
return (
<>
@@ -24,6 +26,25 @@ export default async function TodayPage() {
Hello, {name}
+ {wellnessReady && (
+ <>
+
+ Your wellness
+
+ Built around your actual records, not guessed readiness scores.
+
+
+
+
+ >
+ )}
Progress
+ {process.env.PERSONAL_WELLNESS_ENABLED === "true" && o.canLogMeasurements && (
+
+ )}
{MEASUREMENT_KINDS.filter((k) => o.measurements[k]?.length).map((kind: MeasurementKind) => {
const list = o.measurements[kind]; // newest first
diff --git a/src/app/me/recovery/loading.tsx b/src/app/me/recovery/loading.tsx
new file mode 100644
index 00000000..839c191c
--- /dev/null
+++ b/src/app/me/recovery/loading.tsx
@@ -0,0 +1,7 @@
+export default function Loading() {
+ return (
+
+ Loading recovery…
+
+ );
+}
diff --git a/src/app/me/recovery/page.tsx b/src/app/me/recovery/page.tsx
new file mode 100644
index 00000000..8355c21b
--- /dev/null
+++ b/src/app/me/recovery/page.tsx
@@ -0,0 +1,40 @@
+import { prisma } from "@/lib/prisma";
+import { requireWellnessPage } from "@/lib/personal/wellness-page";
+import { listRecovery } from "@/lib/personal/wellness-recovery";
+import { localDate } from "@/lib/personal/wellness-rules";
+import { RecoveryForm } from "@/components/personal/wellness-recovery";
+
+export default async function RecoveryPage() {
+ const userId = await requireWellnessPage();
+ const [checkIns, profile] = await Promise.all([
+ listRecovery(prisma, userId),
+ prisma.personalProfile.findUnique({ where: { userId }, select: { timezone: true } }),
+ ]);
+ const today = localDate(new Date(), profile?.timezone ?? "UTC");
+ return (
+ <>
+
+ A mindful check-in
+ Recovery
+
+
+
+ History
+ {checkIns.length === 0 ? (
+
+ No check-ins yet. The journal never treats missing data as poor recovery.
+
+ ) : (
+ checkIns.map((x) => (
+
+ {x.localDate}
+
+ Energy {x.energy ?? "—"} · Soreness {x.soreness ?? "—"} · Stress {x.stress ?? "—"}
+
+
+ ))
+ )}
+
+ >
+ );
+}
diff --git a/src/app/me/sleep/loading.tsx b/src/app/me/sleep/loading.tsx
new file mode 100644
index 00000000..b7a631d0
--- /dev/null
+++ b/src/app/me/sleep/loading.tsx
@@ -0,0 +1,7 @@
+export default function Loading() {
+ return (
+
+ Loading sleep…
+
+ );
+}
diff --git a/src/app/me/sleep/page.tsx b/src/app/me/sleep/page.tsx
new file mode 100644
index 00000000..0e888950
--- /dev/null
+++ b/src/app/me/sleep/page.tsx
@@ -0,0 +1,41 @@
+import { prisma } from "@/lib/prisma";
+import { requireWellnessPage } from "@/lib/personal/wellness-page";
+import { listSleep } from "@/lib/personal/wellness-sleep";
+import { sleepMinutes } from "@/lib/personal/wellness-rules";
+import { SleepForm, RemoveSleep } from "@/components/personal/wellness-sleep";
+
+export default async function SleepPage() {
+ const userId = await requireWellnessPage();
+ const entries = await listSleep(prisma, userId);
+ return (
+ <>
+
+
+
+ Your rest
+ {entries.length === 0 ? (
+ Your sleep history will appear after your first entry.
+ ) : (
+ entries.map((s) => (
+
+
+
+ {Math.floor(sleepMinutes(s.startedAt, s.endedAt) / 60)}h{" "}
+ {sleepMinutes(s.startedAt, s.endedAt) % 60}m
+
+
+ {s.endedAt.toLocaleDateString()} · {s.isNap ? "Nap" : "Main sleep"}
+ {s.quality ? " · Quality " + s.quality + "/5" : ""}
+
+
+
+
+ ))
+ )}
+
+ >
+ );
+}
diff --git a/src/app/me/workouts/[id]/loading.tsx b/src/app/me/workouts/[id]/loading.tsx
new file mode 100644
index 00000000..a456b68e
--- /dev/null
+++ b/src/app/me/workouts/[id]/loading.tsx
@@ -0,0 +1,7 @@
+export default function Loading() {
+ return (
+
+ Loading workout…
+
+ );
+}
diff --git a/src/app/me/workouts/[id]/page.tsx b/src/app/me/workouts/[id]/page.tsx
new file mode 100644
index 00000000..f18b86c8
--- /dev/null
+++ b/src/app/me/workouts/[id]/page.tsx
@@ -0,0 +1,42 @@
+import { notFound } from "next/navigation";
+import { prisma } from "@/lib/prisma";
+import { requireWellnessPage } from "@/lib/personal/wellness-page";
+import { RemoveWorkout } from "@/components/personal/wellness-workouts";
+
+export default async function WorkoutDetail({ params }: { params: Promise<{ id: string }> }) {
+ const userId = await requireWellnessPage();
+ const { id } = await params;
+ const w = await prisma.workoutSession.findFirst({
+ where: { id, userId },
+ include: {
+ exercises: {
+ orderBy: { position: "asc" },
+ include: { sets: { orderBy: { position: "asc" } } },
+ },
+ },
+ });
+ if (!w) notFound();
+ return (
+
+ {w.title}
+
+ {w.durationMinutes} minutes · {w.endedAt.toLocaleString()}
+
+ {w.notes ?? "Recorded manually."}
+ {w.exercises.map((e) => (
+
+ {e.name}
+
+ {e.sets.map((s) => (
+ -
+ {s.reps ?? "—"} reps ·{" "}
+ {s.weightGrams === null ? "No weight entered" : s.weightGrams / 1000 + " kg"}
+
+ ))}
+
+
+ ))}
+
+
+ );
+}
diff --git a/src/app/me/workouts/loading.tsx b/src/app/me/workouts/loading.tsx
new file mode 100644
index 00000000..85b3fdf6
--- /dev/null
+++ b/src/app/me/workouts/loading.tsx
@@ -0,0 +1,7 @@
+export default function Loading() {
+ return (
+
+ Loading workouts…
+
+ );
+}
diff --git a/src/app/me/workouts/page.tsx b/src/app/me/workouts/page.tsx
new file mode 100644
index 00000000..7fda0933
--- /dev/null
+++ b/src/app/me/workouts/page.tsx
@@ -0,0 +1,54 @@
+import Link from "next/link";
+import { prisma } from "@/lib/prisma";
+import { requireWellnessPage } from "@/lib/personal/wellness-page";
+import { listWorkouts } from "@/lib/personal/wellness-workouts";
+import { WorkoutLogForm, RemoveWorkout } from "@/components/personal/wellness-workouts";
+
+export default async function WorkoutsPage() {
+ const userId = await requireWellnessPage();
+ const workouts = await listWorkouts(prisma, userId);
+ return (
+ <>
+
+ Training journal
+ My workouts
+
+
+
+
+
Completed sessions
+
+ My goals
+
+
+ {workouts.length === 0 ? (
+
+ Log your first completed session to start a real progress history.
+
+ ) : (
+ workouts.map((w) => (
+
+
+ {w.title}
+ {w.durationMinutes} min
+
+
+ {w.activityKey.replaceAll("-", " ")} · {w.endedAt.toLocaleDateString()}
+
+ {w.exercises.length > 0 && (
+
+ {w.exercises.map((e) => (
+ -
+ {e.name} · {e.sets.length} {e.sets.length === 1 ? "set" : "sets"}
+
+ ))}
+
+ )}
+
+
+ ))
+ )}
+
+ >
+ );
+}
diff --git a/src/components/personal/personal-nav.tsx b/src/components/personal/personal-nav.tsx
index cec53b9f..27643bc4 100644
--- a/src/components/personal/personal-nav.tsx
+++ b/src/components/personal/personal-nav.tsx
@@ -7,7 +7,7 @@ import { Activity, Dumbbell, LineChart, Sun, UserRound } from "lucide-react";
const TABS = [
{ href: "/me", label: "Today", Icon: Sun },
{ href: "/me/body", label: "Body", Icon: Dumbbell },
- { href: "/me/activity", label: "Activity", Icon: Activity },
+ { href: "/me/activity", label: "Train", Icon: Activity },
{ href: "/me/progress", label: "Progress", Icon: LineChart },
{ href: "/me/profile", label: "Profile", Icon: UserRound },
] as const;
diff --git a/src/components/personal/personal-shell.tsx b/src/components/personal/personal-shell.tsx
index d4a9cf8b..b9937404 100644
--- a/src/components/personal/personal-shell.tsx
+++ b/src/components/personal/personal-shell.tsx
@@ -1,4 +1,5 @@
import Link from "next/link";
+import { Suspense } from "react";
import { ArrowLeft } from "lucide-react";
import { ClubKeepBrand } from "@/components/human-motion/media-components";
import { ClubThemeToggle } from "@/components/clubs/theme-toggle";
@@ -24,7 +25,9 @@ export function PersonalShell({ children }: { children: React.ReactNode }) {
-
+
+
+
{children}
diff --git a/src/components/personal/personal.css b/src/components/personal/personal.css
index 84f70ad1..98fe8759 100644
--- a/src/components/personal/personal.css
+++ b/src/components/personal/personal.css
@@ -126,3 +126,61 @@
stroke-linecap: round;
stroke-linejoin: round;
}
+
+.hm-me-field textarea {
+ width: 100%;
+ min-height: 92px;
+ box-sizing: border-box;
+ padding: 0.75rem;
+ border-radius: 14px;
+ border: 1px solid var(--hm-line);
+ background: var(--hm-bg);
+ color: var(--hm-text);
+ font: inherit;
+ font-weight: 400;
+}
+.hm-me-launch-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 0.625rem;
+}
+.hm-me-launch-grid a {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ min-height: 52px;
+ padding: 0.5rem;
+ border: 1px solid var(--hm-line);
+ border-radius: 14px;
+ text-decoration: none;
+ color: var(--hm-text);
+ background: var(--hm-raised);
+ font-weight: 600;
+}
+.hm-me-launch-grid a:focus-visible {
+ outline: 3px solid var(--hm-action);
+ outline-offset: 2px;
+}
+.hm-me-card progress {
+ width: 100%;
+ height: 12px;
+ accent-color: var(--hm-sage-deep);
+}
+.hm-me-insight-days {
+ padding: 0;
+ margin: 0;
+ list-style: none;
+}
+.hm-me-insight-days li {
+ min-height: 36px;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.5rem;
+ justify-content: space-between;
+ border-bottom: 1px solid var(--hm-line);
+}
+@media (min-width: 620px) {
+ .hm-me-launch-grid {
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+ }
+}
diff --git a/src/components/personal/wellness-goals.tsx b/src/components/personal/wellness-goals.tsx
new file mode 100644
index 00000000..7e25de12
--- /dev/null
+++ b/src/components/personal/wellness-goals.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import { postJson } from "@/components/personal/post-json";
+
+export function GoalForm() {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ function submit(data: FormData) {
+ const metric = String(data.get("metric"));
+ const title = String(data.get("title"));
+ const cadence = String(data.get("cadence"));
+ const target = Number(data.get("target"));
+ start(async () => {
+ const result = await postJson("/api/me/wellness/goals", { metric, title, cadence, target });
+ setMessage(result.ok ? "Goal added." : result.error);
+ if (result.ok) router.refresh();
+ });
+ }
+ return (
+
+ );
+}
+
+export function GoalActions({ id, status }: { id: string; status: string }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ function action(path: string, body: object) {
+ start(async () => {
+ const res = await postJson(path, body);
+ setMessage(res.ok ? "Updated." : res.error);
+ if (res.ok) router.refresh();
+ });
+ }
+ return (
+
+
+
+ {message && (
+
+ {message}
+
+ )}
+
+ );
+}
diff --git a/src/components/personal/wellness-insights.tsx b/src/components/personal/wellness-insights.tsx
new file mode 100644
index 00000000..542cc4f7
--- /dev/null
+++ b/src/components/personal/wellness-insights.tsx
@@ -0,0 +1,67 @@
+import Link from "next/link";
+import { prisma } from "@/lib/prisma";
+import { wellnessInsights } from "@/lib/personal/wellness-insights";
+
+export async function WellnessInsightsSection({ userId }: { userId: string }) {
+ const insights = await wellnessInsights(prisma, userId);
+ return (
+
+
+
Wellness progress
+
+ Goals
+
+
+ {insights.disclosure}
+
+
+ Workouts this week
+ {insights.thisWeek.workouts}
+
+
+ Active minutes this week
+ {insights.thisWeek.activityMinutes}
+
+
+ Logged sleep this week
+ {insights.thisWeek.sleepMinutes} min
+
+
+ Water logged this week
+ {insights.thisWeek.hydrationMl} mL
+
+
+ Active goals
+ {insights.goals.length === 0 ? (
+ Add a goal to see your measured progress.
+ ) : (
+ insights.goals.map((g) => (
+
+
+ {g.title}
+
+ {g.achieved} / {g.target}
+
+
+
+
+ ))
+ )}
+ Last recorded days
+
+ {insights.days.slice(-14).map((d) => (
+ -
+ {d.date}
+
+ {d.workouts} sessions · {d.minutes} min
+
+
+ ))}
+
+
+ );
+}
diff --git a/src/components/personal/wellness-nutrition.tsx b/src/components/personal/wellness-nutrition.tsx
new file mode 100644
index 00000000..c75dbe1b
--- /dev/null
+++ b/src/components/personal/wellness-nutrition.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import { postJson } from "./post-json";
+
+export function MealForm() {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ const [requestId, setRequestId] = useState(() => crypto.randomUUID());
+ function submit(data: FormData) {
+ const lines = String(data.get("foods") ?? "")
+ .split("\n")
+ .map((x) => x.trim())
+ .filter(Boolean);
+ const items = lines.map((line) => {
+ const [name, portion, calories, protein] = line.split("|").map((x) => x.trim());
+ return {
+ name,
+ ...(portion ? { portionGrams: Number(portion) } : {}),
+ ...(calories ? { caloriesKcal: Number(calories) } : {}),
+ ...(protein ? { proteinGrams: Number(protein) } : {}),
+ };
+ });
+ if (!items.length) {
+ setMessage("Add at least one food.");
+ return;
+ }
+ start(async () => {
+ const result = await postJson("/api/me/wellness/meals", {
+ requestId,
+ mealType: String(data.get("mealType")),
+ eatenAt: new Date().toISOString(),
+ items,
+ });
+ setMessage(result.ok ? "Meal added." : result.error);
+ if (result.ok) {
+ setRequestId(crypto.randomUUID());
+ router.refresh();
+ }
+ });
+ }
+ return (
+
+ );
+}
+
+export function HydrationForm() {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ const [requestId, setRequestId] = useState(() => crypto.randomUUID());
+ function submit(data: FormData) {
+ start(async () => {
+ const res = await postJson("/api/me/wellness/hydration", {
+ requestId,
+ volumeMl: Number(data.get("volume")),
+ takenAt: new Date().toISOString(),
+ });
+ setMessage(res.ok ? "Water logged." : res.error);
+ if (res.ok) {
+ setRequestId(crypto.randomUUID());
+ router.refresh();
+ }
+ });
+ }
+ return (
+
+ );
+}
+
+export function RemoveNutrition({ id, kind }: { id: string; kind: "meals" | "hydration" }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ return (
+
+
+ {message && (
+
+ {message}
+
+ )}
+
+ );
+}
diff --git a/src/components/personal/wellness-recovery.tsx b/src/components/personal/wellness-recovery.tsx
new file mode 100644
index 00000000..2af4c40d
--- /dev/null
+++ b/src/components/personal/wellness-recovery.tsx
@@ -0,0 +1,75 @@
+"use client";
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import { postJson } from "./post-json";
+const METRICS = [
+ ["energy", "Energy"],
+ ["soreness", "Muscle soreness"],
+ ["stress", "Perceived stress"],
+ ["satisfaction", "Sleep satisfaction"],
+] as const;
+export function RecoveryForm({ today }: { today: string }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ function submit(form: FormData) {
+ const ratings = Object.fromEntries(
+ METRICS.flatMap(([key]) => {
+ const val = Number(form.get(key));
+ return val ? [[key, val]] : [];
+ })
+ );
+ start(async () => {
+ const res = await postJson("/api/me/wellness/recovery", {
+ localDate: String(form.get("localDate")),
+ ...ratings,
+ ...(String(form.get("notes") ?? "").trim()
+ ? { notes: String(form.get("notes")).trim() }
+ : {}),
+ });
+ setMessage(res.ok ? "Check-in saved." : res.error);
+ if (res.ok) router.refresh();
+ });
+ }
+ return (
+
+ );
+}
diff --git a/src/components/personal/wellness-sleep.tsx b/src/components/personal/wellness-sleep.tsx
new file mode 100644
index 00000000..7999dc56
--- /dev/null
+++ b/src/components/personal/wellness-sleep.tsx
@@ -0,0 +1,106 @@
+"use client";
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import { postJson } from "./post-json";
+
+export function SleepForm() {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ const [requestId, setRequestId] = useState(() => crypto.randomUUID());
+ function submit(data: FormData) {
+ const startedAt = new Date(String(data.get("start")));
+ const endedAt = new Date(String(data.get("end")));
+ if (!Number.isFinite(startedAt.getTime()) || !Number.isFinite(endedAt.getTime())) {
+ setMessage("Choose your sleep and wake times.");
+ return;
+ }
+ const quality = Number(data.get("quality"));
+ start(async () => {
+ const res = await postJson("/api/me/wellness/sleep", {
+ requestId,
+ startedAt: startedAt.toISOString(),
+ endedAt: endedAt.toISOString(),
+ ...(quality ? { quality } : {}),
+ isNap: data.get("nap") === "on",
+ });
+ setMessage(res.ok ? "Sleep recorded." : res.error);
+ if (res.ok) {
+ setRequestId(crypto.randomUUID());
+ router.refresh();
+ }
+ });
+ }
+ return (
+
+ );
+}
+
+export function RemoveSleep({ id }: { id: string }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ return (
+
+
+ {message && (
+
+ {message}
+
+ )}
+
+ );
+}
diff --git a/src/components/personal/wellness-workouts.tsx b/src/components/personal/wellness-workouts.tsx
new file mode 100644
index 00000000..2e8d9beb
--- /dev/null
+++ b/src/components/personal/wellness-workouts.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { useState, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import { ACTIVITIES } from "@/lib/personal/muscle-map";
+import { postJson } from "./post-json";
+
+export function WorkoutLogForm() {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ const [requestId, setRequestId] = useState(() => crypto.randomUUID());
+ function submit(form: FormData) {
+ const durationMinutes = Number(form.get("duration"));
+ const endedAt = new Date();
+ const startedAt = new Date(endedAt.getTime() - durationMinutes * 60000);
+ const name = String(form.get("exercise") ?? "").trim();
+ const reps = Number(form.get("reps"));
+ const weight = Number(form.get("weight"));
+ const exercises = name
+ ? [
+ {
+ name,
+ sets: [
+ {
+ ...(reps > 0 ? { reps } : {}),
+ ...(weight > 0 ? { weightGrams: Math.round(weight * 1000) } : {}),
+ },
+ ],
+ },
+ ]
+ : [];
+ start(async () => {
+ const result = await postJson("/api/me/wellness/workouts", {
+ requestId,
+ title: String(form.get("title")),
+ activityKey: String(form.get("activity")),
+ durationMinutes,
+ startedAt: startedAt.toISOString(),
+ endedAt: endedAt.toISOString(),
+ exercises,
+ });
+ setMessage(result.ok ? "Workout saved." : result.error);
+ if (result.ok) {
+ setRequestId(crypto.randomUUID());
+ router.refresh();
+ }
+ });
+ }
+ return (
+
+ );
+}
+export function RemoveWorkout({ id }: { id: string }) {
+ const router = useRouter();
+ const [pending, start] = useTransition();
+ const [message, setMessage] = useState("");
+ return (
+
+
+ {message && (
+
+ {message}
+
+ )}
+
+ );
+}
diff --git a/src/lib/personal/personal-service.ts b/src/lib/personal/personal-service.ts
index a049694f..d197aec4 100644
--- a/src/lib/personal/personal-service.ts
+++ b/src/lib/personal/personal-service.ts
@@ -219,7 +219,18 @@ export async function setClubSignalConsent(
export async function exportPersonalData(db: PrismaClient, userId: string, now = new Date()) {
const profile = await ensureProfile(db, userId);
- const [measurements, activities, consents] = await Promise.all([
+ const [
+ measurements,
+ activities,
+ consents,
+ goals,
+ workouts,
+ sleep,
+ meals,
+ hydration,
+ recovery,
+ sources,
+ ] = await Promise.all([
db.personalMeasurement.findMany({
where: { userId },
orderBy: { measuredAt: "asc" },
@@ -233,6 +244,16 @@ export async function exportPersonalData(db: PrismaClient, userId: string, now =
where: { userId },
select: { clubId: true, enabled: true },
}),
+ db.personalGoalInstance.findMany({ where: { userId } }),
+ db.workoutSession.findMany({
+ where: { userId },
+ include: { exercises: { include: { sets: true } } },
+ }),
+ db.sleepSession.findMany({ where: { userId } }),
+ db.mealEntry.findMany({ where: { userId }, include: { items: true } }),
+ db.hydrationEntry.findMany({ where: { userId } }),
+ db.recoveryCheckIn.findMany({ where: { userId } }),
+ db.wellnessSourceRecord.findMany({ where: { userId } }),
]);
const units = profile.units as Units;
return {
@@ -253,6 +274,7 @@ export async function exportPersonalData(db: PrismaClient, userId: string, now =
})),
activities,
clubSignalConsents: consents,
+ wellness: { goals, workouts, sleep, meals, hydration, recovery, sources },
};
}
@@ -262,9 +284,25 @@ export async function deleteAllPersonalData(db: PrismaClient, userId: string) {
db.personalMeasurement.deleteMany({ where: { userId } }),
db.personalActivity.deleteMany({ where: { userId } }),
db.personalClubSignalConsent.deleteMany({ where: { userId } }),
+ // Child exercise/meal rows cascade; keep account and club membership intact.
+ db.personalGoalInstance.deleteMany({ where: { userId } }),
+ db.workoutSession.deleteMany({ where: { userId } }),
+ db.sleepSession.deleteMany({ where: { userId } }),
+ db.mealEntry.deleteMany({ where: { userId } }),
+ db.hydrationEntry.deleteMany({ where: { userId } }),
+ db.recoveryCheckIn.deleteMany({ where: { userId } }),
+ db.wellnessSourceRecord.deleteMany({ where: { userId } }),
db.personalProfile.updateMany({
where: { userId },
- data: { birthYear: null, heightMm: null, goal: null, units: "METRIC" },
+ data: {
+ displayName: null,
+ birthYear: null,
+ heightMm: null,
+ goal: null,
+ units: "METRIC",
+ locale: "en",
+ timezone: "UTC",
+ },
}),
]);
}
diff --git a/src/lib/personal/wellness-goals.ts b/src/lib/personal/wellness-goals.ts
new file mode 100644
index 00000000..826febe1
--- /dev/null
+++ b/src/lib/personal/wellness-goals.ts
@@ -0,0 +1,57 @@
+import type { PrismaClient } from "@/generated/prisma/client";
+import { OnboardingError } from "@/lib/club-onboarding";
+import type { GoalInput } from "@/lib/validations/wellness";
+import { checkedDate } from "./wellness-policy";
+
+export async function listGoals(db: PrismaClient, userId: string) {
+ return db.personalGoalInstance.findMany({
+ where: { userId },
+ orderBy: [{ status: "asc" }, { createdAt: "desc" }],
+ take: 100,
+ });
+}
+
+export async function createGoal(db: PrismaClient, userId: string, input: GoalInput) {
+ const now = new Date();
+ const endsAt = input.endsAt
+ ? checkedDate(input.endsAt, new Date(now.getTime() + 10 * 365 * 86400000))
+ : null;
+ if (endsAt && endsAt <= now)
+ throw new OnboardingError(400, "Goal end date must be in the future.");
+ const current = await db.personalGoalInstance.count({ where: { userId, status: "ACTIVE" } });
+ if (current >= 20) throw new OnboardingError(409, "Archive an existing goal before adding more.");
+ const goal = await db.personalGoalInstance.create({
+ data: {
+ userId,
+ title: input.title,
+ metric: input.metric,
+ cadence: input.cadence,
+ target: input.target,
+ endsAt,
+ },
+ select: { id: true },
+ });
+ return { id: goal.id };
+}
+
+export async function changeGoal(
+ db: PrismaClient,
+ userId: string,
+ input: {
+ id: string;
+ title?: string;
+ target?: number;
+ status?: "ACTIVE" | "PAUSED" | "ARCHIVED";
+ }
+) {
+ const changed = await db.personalGoalInstance.updateMany({
+ where: { id: input.id, userId },
+ data: { title: input.title, target: input.target, status: input.status },
+ });
+ if (!changed.count) throw new OnboardingError(404, "Goal not found.");
+}
+
+export async function removeGoal(db: PrismaClient, userId: string, id: string) {
+ const result = await db.personalGoalInstance.deleteMany({ where: { id, userId } });
+ if (!result.count) throw new OnboardingError(404, "Goal not found.");
+}
diff --git a/src/lib/personal/wellness-http.ts b/src/lib/personal/wellness-http.ts
new file mode 100644
index 00000000..ed199b13
--- /dev/null
+++ b/src/lib/personal/wellness-http.ts
@@ -0,0 +1,53 @@
+import type { NextRequest } from "next/server";
+import type { z } from "zod";
+import type { PrismaClient } from "@/generated/prisma/client";
+import { auth } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { jsonPrivate, onboardingFailure } from "@/lib/onboarding-http";
+import { personalPost } from "@/lib/personal/personal-http";
+import { assertWellnessAdult, assertWellnessEnabled } from "@/lib/personal/wellness-policy";
+
+/** Every Personal wellness read and write enforces the rollout AND adult policy server-side. */
+export async function wellnessPost(
+ request: NextRequest,
+ scope: string,
+ limit: number,
+ schema: z.ZodType,
+ handler: (db: PrismaClient, userId: string, input: T) => Promise
+): Promise {
+ try {
+ assertWellnessEnabled();
+ return await personalPost(
+ request,
+ "wellness-" + scope,
+ limit,
+ schema,
+ async (userId, input) => {
+ await assertWellnessAdult(prisma, userId);
+ return handler(prisma, userId, input);
+ }
+ );
+ } catch (error) {
+ return onboardingFailure(error);
+ }
+}
+
+export async function wellnessRead(
+ request: Request,
+ handler: (db: PrismaClient, userId: string) => Promise
+): Promise {
+ const site = request.headers.get("sec-fetch-site");
+ if (site && site !== "same-origin" && site !== "none") {
+ return jsonPrivate({ error: "Forbidden" }, 403);
+ }
+ try {
+ assertWellnessEnabled();
+ const session = await auth.api.getSession({ headers: request.headers });
+ if (!session?.user) return jsonPrivate({ error: "Sign in first" }, 401);
+ if (!session.user.emailVerified) return jsonPrivate({ error: "Verify your account" }, 403);
+ await assertWellnessAdult(prisma, session.user.id);
+ return jsonPrivate({ ok: true, data: await handler(prisma, session.user.id) });
+ } catch (error) {
+ return onboardingFailure(error);
+ }
+}
diff --git a/src/lib/personal/wellness-insights.ts b/src/lib/personal/wellness-insights.ts
new file mode 100644
index 00000000..fdbaf4c9
--- /dev/null
+++ b/src/lib/personal/wellness-insights.ts
@@ -0,0 +1,147 @@
+import type { PrismaClient } from "@/generated/prisma/client";
+import { localDate, mondayUtc, safeRate, sleepMinutes } from "./wellness-rules";
+
+export async function wellnessInsights(db: PrismaClient, userId: string, now = new Date()) {
+ const since = new Date(now.getTime() - 90 * 86400000);
+ const [profile, workouts, sleeps, waters, meals, recovery, goals] = await Promise.all([
+ db.personalProfile.findUnique({ where: { userId }, select: { timezone: true } }),
+ db.workoutSession.findMany({
+ where: { userId, endedAt: { gte: since, lte: now } },
+ select: { endedAt: true, durationMinutes: true },
+ orderBy: { endedAt: "asc" },
+ take: 5000,
+ }),
+ db.sleepSession.findMany({
+ where: { userId, endedAt: { gte: since, lte: now } },
+ select: { startedAt: true, endedAt: true, isNap: true },
+ take: 5000,
+ }),
+ db.hydrationEntry.findMany({
+ where: { userId, takenAt: { gte: since, lte: now } },
+ select: { takenAt: true, volumeMl: true },
+ take: 10000,
+ }),
+ db.mealEntry.findMany({
+ where: { userId, eatenAt: { gte: since, lte: now } },
+ select: { eatenAt: true },
+ take: 5000,
+ }),
+ db.recoveryCheckIn.findMany({
+ where: { userId, localDate: { gte: since.toISOString().slice(0, 10) } },
+ select: { localDate: true, energy: true, soreness: true, stress: true, satisfaction: true },
+ }),
+ db.personalGoalInstance.findMany({ where: { userId, status: "ACTIVE" }, take: 20 }),
+ ]);
+ const zone = profile?.timezone ?? "UTC";
+ const days = new Map<
+ string,
+ {
+ date: string;
+ workouts: number;
+ minutes: number;
+ sleepMinutes: number | null;
+ hydrationMl: number | null;
+ meals: number;
+ energy: number | null;
+ }
+ >();
+ const day = (d: string) => {
+ let entry = days.get(d);
+ if (!entry) {
+ entry = {
+ date: d,
+ workouts: 0,
+ minutes: 0,
+ sleepMinutes: null,
+ hydrationMl: null,
+ meals: 0,
+ energy: null,
+ };
+ days.set(d, entry);
+ }
+ return entry;
+ };
+ for (const w of workouts) {
+ const d = day(localDate(w.endedAt, zone));
+ d.workouts += 1;
+ d.minutes += w.durationMinutes;
+ }
+ for (const s of sleeps) {
+ if (s.isNap) continue; // Main sleep only; naps remain accessible in sleep history.
+ const d = day(localDate(s.endedAt, zone));
+ d.sleepMinutes = (d.sleepMinutes ?? 0) + sleepMinutes(s.startedAt, s.endedAt);
+ }
+ for (const w of waters) {
+ const d = day(localDate(w.takenAt, zone));
+ d.hydrationMl = (d.hydrationMl ?? 0) + w.volumeMl;
+ }
+ for (const m of meals) day(localDate(m.eatenAt, zone)).meals += 1;
+ for (const r of recovery) day(r.localDate).energy = r.energy;
+ const today = localDate(now, zone);
+ const weekStart = mondayUtc(new Date(today + "T12:00:00Z"))
+ .toISOString()
+ .slice(0, 10);
+ const weekly = [...days.values()].filter((x) => x.date >= weekStart && x.date <= today);
+ const thisWeek = weekly.reduce(
+ (a, x) => ({
+ workouts: a.workouts + x.workouts,
+ activityMinutes: a.activityMinutes + x.minutes,
+ sleepMinutes: a.sleepMinutes + (x.sleepMinutes ?? 0),
+ hydrationMl: a.hydrationMl + (x.hydrationMl ?? 0),
+ }),
+ { workouts: 0, activityMinutes: 0, sleepMinutes: 0, hydrationMl: 0 }
+ );
+ const goalProgress = await Promise.all(
+ goals.map(async (goal) => {
+ // TOTAL goals must not silently truncate to the 90-day chart horizon.
+ const start = goal.cadence === "WEEKLY" ? weekStart : localDate(goal.startsAt, zone);
+ const end = goal.endsAt && goal.endsAt < now ? goal.endsAt : now;
+ const from = new Date(start + "T00:00:00Z");
+ let achieved = 0;
+ if (goal.metric === "WORKOUT_SESSIONS") {
+ achieved = await db.workoutSession.count({
+ where: { userId, endedAt: { gte: from, lte: end } },
+ });
+ } else if (goal.metric === "ACTIVITY_MINUTES") {
+ const a = await db.workoutSession.aggregate({
+ where: { userId, endedAt: { gte: from, lte: end } },
+ _sum: { durationMinutes: true },
+ });
+ achieved = a._sum.durationMinutes ?? 0;
+ } else if (goal.metric === "HYDRATION_ML") {
+ const a = await db.hydrationEntry.aggregate({
+ where: { userId, takenAt: { gte: from, lte: end } },
+ _sum: { volumeMl: true },
+ });
+ achieved = a._sum.volumeMl ?? 0;
+ } else {
+ const records = await db.sleepSession.findMany({
+ where: { userId, endedAt: { gte: from, lte: end }, isNap: false },
+ select: { startedAt: true, endedAt: true },
+ });
+ achieved = records.reduce((sum, s) => sum + sleepMinutes(s.startedAt, s.endedAt), 0);
+ }
+ return {
+ id: goal.id,
+ title: goal.title,
+ metric: goal.metric,
+ cadence: goal.cadence,
+ target: goal.target,
+ achieved,
+ percentage: safeRate(achieved, goal.target),
+ };
+ })
+ );
+ return {
+ today,
+ timezone: zone,
+ thisWeek,
+ goals: goalProgress,
+ days: [...days.values()]
+ .filter((x) => x.date <= today)
+ .sort((a, b) => a.date.localeCompare(b.date))
+ .slice(-90),
+ disclosure:
+ "Manual observations and completed workouts only. Missing data is not zero. No clinical recovery score.",
+ };
+}
diff --git a/src/lib/personal/wellness-nutrition.ts b/src/lib/personal/wellness-nutrition.ts
new file mode 100644
index 00000000..e83f549f
--- /dev/null
+++ b/src/lib/personal/wellness-nutrition.ts
@@ -0,0 +1,79 @@
+import type { PrismaClient } from "@/generated/prisma/client";
+import { OnboardingError } from "@/lib/club-onboarding";
+import type { HydrationInput, MealInput } from "@/lib/validations/wellness";
+import { checkedDate } from "./wellness-policy";
+
+export async function listNutrition(db: PrismaClient, userId: string) {
+ const [meals, hydration] = await Promise.all([
+ db.mealEntry.findMany({
+ where: { userId },
+ orderBy: { eatenAt: "desc" },
+ take: 100,
+ include: { items: { orderBy: { position: "asc" } } },
+ }),
+ db.hydrationEntry.findMany({ where: { userId }, orderBy: { takenAt: "desc" }, take: 100 }),
+ ]);
+ return { meals, hydration };
+}
+
+export async function recordMeal(db: PrismaClient, userId: string, input: MealInput) {
+ const eatenAt = checkedDate(input.eatenAt);
+ const existing = await db.mealEntry.findUnique({
+ where: { userId_requestId: { userId, requestId: input.requestId } },
+ });
+ if (existing) return { id: existing.id, replayed: true };
+ try {
+ const meal = await db.mealEntry.create({
+ data: {
+ userId,
+ requestId: input.requestId,
+ mealType: input.mealType,
+ eatenAt,
+ notes: input.notes,
+ items: { create: input.items.map((item, position) => ({ ...item, position })) },
+ },
+ select: { id: true },
+ });
+ return { id: meal.id, replayed: false };
+ } catch (error) {
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "P2002") {
+ const row = await db.mealEntry.findUnique({
+ where: { userId_requestId: { userId, requestId: input.requestId } },
+ });
+ if (row) return { id: row.id, replayed: true };
+ }
+ throw error;
+ }
+}
+
+export async function recordHydration(db: PrismaClient, userId: string, input: HydrationInput) {
+ const takenAt = checkedDate(input.takenAt);
+ const existing = await db.hydrationEntry.findUnique({
+ where: { userId_requestId: { userId, requestId: input.requestId } },
+ });
+ if (existing) return { id: existing.id, replayed: true };
+ try {
+ const row = await db.hydrationEntry.create({
+ data: { userId, requestId: input.requestId, volumeMl: input.volumeMl, takenAt },
+ select: { id: true },
+ });
+ return { id: row.id, replayed: false };
+ } catch (error) {
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "P2002") {
+ const row = await db.hydrationEntry.findUnique({
+ where: { userId_requestId: { userId, requestId: input.requestId } },
+ });
+ if (row) return { id: row.id, replayed: true };
+ }
+ throw error;
+ }
+}
+
+export async function removeMeal(db: PrismaClient, userId: string, id: string) {
+ const removed = await db.mealEntry.deleteMany({ where: { id, userId } });
+ if (!removed.count) throw new OnboardingError(404, "Meal not found.");
+}
+export async function removeHydration(db: PrismaClient, userId: string, id: string) {
+ const removed = await db.hydrationEntry.deleteMany({ where: { id, userId } });
+ if (!removed.count) throw new OnboardingError(404, "Water entry not found.");
+}
diff --git a/src/lib/personal/wellness-page.ts b/src/lib/personal/wellness-page.ts
new file mode 100644
index 00000000..2468bbe9
--- /dev/null
+++ b/src/lib/personal/wellness-page.ts
@@ -0,0 +1,12 @@
+import { notFound } from "next/navigation";
+import { prisma } from "@/lib/prisma";
+import { requireSession } from "@/lib/required-session";
+import { assertWellnessAdult } from "@/lib/personal/wellness-policy";
+
+/** Use on every private wellness page; no page relies solely on the layout for authentication. */
+export async function requireWellnessPage(): Promise {
+ if (process.env.PERSONAL_WELLNESS_ENABLED !== "true") notFound();
+ const session = await requireSession();
+ await assertWellnessAdult(prisma, session.user.id);
+ return session.user.id;
+}
diff --git a/src/lib/personal/wellness-policy.ts b/src/lib/personal/wellness-policy.ts
new file mode 100644
index 00000000..142d3fe5
--- /dev/null
+++ b/src/lib/personal/wellness-policy.ts
@@ -0,0 +1,36 @@
+import { OnboardingError } from "@/lib/club-onboarding";
+import type { PrismaClient } from "@/generated/prisma/client";
+
+// Feature off until production age, privacy and operator gates are accepted.
+export function assertWellnessEnabled(): void {
+ if (process.env.PERSONAL_WELLNESS_ENABLED !== "true") {
+ throw new OnboardingError(503, "Wellness is not enabled yet.");
+ }
+}
+
+export async function assertWellnessAdult(
+ db: PrismaClient,
+ userId: string,
+ now = new Date()
+): Promise {
+ const profile = await db.personalProfile.findUnique({
+ where: { userId },
+ select: { birthYear: true },
+ });
+ // Conservative age rule with birth-year-only profiles; no unsupported guardian flow.
+ if (!profile?.birthYear || now.getUTCFullYear() - profile.birthYear < 19) {
+ throw new OnboardingError(403, "Adult Personal access is required for this feature.");
+ }
+}
+
+export function checkedDate(value: string, now = new Date()): Date {
+ const when = new Date(value);
+ if (
+ !Number.isFinite(when.getTime()) ||
+ when.getUTCFullYear() < 2000 ||
+ when.getTime() > now.getTime() + 5 * 60_000
+ ) {
+ throw new OnboardingError(400, "Choose a valid date that is not in the future.");
+ }
+ return when;
+}
diff --git a/src/lib/personal/wellness-recovery.ts b/src/lib/personal/wellness-recovery.ts
new file mode 100644
index 00000000..79b24dc8
--- /dev/null
+++ b/src/lib/personal/wellness-recovery.ts
@@ -0,0 +1,41 @@
+import type { PrismaClient } from "@/generated/prisma/client";
+import { OnboardingError } from "@/lib/club-onboarding";
+import type { RecoveryInput } from "@/lib/validations/wellness";
+import { localDate } from "./wellness-rules";
+
+export async function listRecovery(db: PrismaClient, userId: string) {
+ return db.recoveryCheckIn.findMany({
+ where: { userId },
+ orderBy: { localDate: "desc" },
+ take: 90,
+ });
+}
+
+export async function saveRecovery(db: PrismaClient, userId: string, input: RecoveryInput) {
+ const profile = await db.personalProfile.findUnique({
+ where: { userId },
+ select: { timezone: true },
+ });
+ const today = localDate(new Date(), profile?.timezone ?? "UTC");
+ if (input.localDate > today || input.localDate < "2000-01-01") {
+ throw new OnboardingError(400, "Choose a day that has already started.");
+ }
+ const data = {
+ energy: input.energy,
+ soreness: input.soreness,
+ stress: input.stress,
+ satisfaction: input.satisfaction,
+ notes: input.notes,
+ };
+ const row = await db.recoveryCheckIn.upsert({
+ where: { userId_localDate: { userId, localDate: input.localDate } },
+ create: { userId, localDate: input.localDate, ...data },
+ update: data,
+ select: { id: true },
+ });
+ return { id: row.id };
+}
+export async function removeRecovery(db: PrismaClient, userId: string, id: string) {
+ const row = await db.recoveryCheckIn.deleteMany({ where: { id, userId } });
+ if (!row.count) throw new OnboardingError(404, "Check-in not found.");
+}
diff --git a/src/lib/personal/wellness-rules.ts b/src/lib/personal/wellness-rules.ts
new file mode 100644
index 00000000..947c0060
--- /dev/null
+++ b/src/lib/personal/wellness-rules.ts
@@ -0,0 +1,26 @@
+/** Pure user-facing math: absent observations stay null, never zero. */
+export function sleepMinutes(startedAt: Date, endedAt: Date): number {
+ return Math.round((endedAt.getTime() - startedAt.getTime()) / 60000);
+}
+export function localDate(at: Date, zone: string): string {
+ try {
+ const parts = new Intl.DateTimeFormat("en-GB", {
+ timeZone: zone,
+ day: "2-digit",
+ month: "2-digit",
+ year: "numeric",
+ }).formatToParts(at);
+ const part = (name: string) => parts.find((x) => x.type === name)?.value ?? "";
+ return part("year") + "-" + part("month") + "-" + part("day");
+ } catch {
+ return at.toISOString().slice(0, 10);
+ }
+}
+export function mondayUtc(date: Date): Date {
+ const result = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
+ result.setUTCDate(result.getUTCDate() - ((result.getUTCDay() + 6) % 7));
+ return result;
+}
+export function safeRate(numerator: number, denominator: number): number | null {
+ return denominator <= 0 ? null : Math.round((numerator / denominator) * 100);
+}
diff --git a/src/lib/personal/wellness-sleep.ts b/src/lib/personal/wellness-sleep.ts
new file mode 100644
index 00000000..1d3cf47d
--- /dev/null
+++ b/src/lib/personal/wellness-sleep.ts
@@ -0,0 +1,50 @@
+import type { PrismaClient } from "@/generated/prisma/client";
+import { OnboardingError } from "@/lib/club-onboarding";
+import type { SleepInput } from "@/lib/validations/wellness";
+import { checkedDate } from "./wellness-policy";
+import { sleepMinutes } from "./wellness-rules";
+
+export async function listSleep(db: PrismaClient, userId: string) {
+ return db.sleepSession.findMany({ where: { userId }, orderBy: { endedAt: "desc" }, take: 100 });
+}
+
+export async function recordSleep(db: PrismaClient, userId: string, input: SleepInput) {
+ const startedAt = checkedDate(input.startedAt);
+ const endedAt = checkedDate(input.endedAt);
+ const minutes = sleepMinutes(startedAt, endedAt);
+ if (minutes < 1 || minutes >= 1440) {
+ throw new OnboardingError(400, "Sleep must be between one minute and under 24 hours.");
+ }
+ const existing = await db.sleepSession.findUnique({
+ where: { userId_requestId: { userId, requestId: input.requestId } },
+ });
+ if (existing) return { id: existing.id, replayed: true };
+ try {
+ const row = await db.sleepSession.create({
+ data: {
+ userId,
+ requestId: input.requestId,
+ startedAt,
+ endedAt,
+ quality: input.quality,
+ isNap: input.isNap,
+ source: "MANUAL",
+ },
+ select: { id: true },
+ });
+ return { id: row.id, replayed: false };
+ } catch (error) {
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "P2002") {
+ const row = await db.sleepSession.findUnique({
+ where: { userId_requestId: { userId, requestId: input.requestId } },
+ });
+ if (row) return { id: row.id, replayed: true };
+ }
+ throw error;
+ }
+}
+
+export async function removeSleep(db: PrismaClient, userId: string, id: string) {
+ const deleted = await db.sleepSession.deleteMany({ where: { id, userId } });
+ if (!deleted.count) throw new OnboardingError(404, "Sleep record not found.");
+}
diff --git a/src/lib/personal/wellness-workouts.ts b/src/lib/personal/wellness-workouts.ts
new file mode 100644
index 00000000..87f38581
--- /dev/null
+++ b/src/lib/personal/wellness-workouts.ts
@@ -0,0 +1,69 @@
+import type { PrismaClient } from "@/generated/prisma/client";
+import { OnboardingError } from "@/lib/club-onboarding";
+import type { WorkoutInput } from "@/lib/validations/wellness";
+import { checkedDate } from "./wellness-policy";
+
+export async function listWorkouts(db: PrismaClient, userId: string) {
+ return db.workoutSession.findMany({
+ where: { userId },
+ orderBy: { endedAt: "desc" },
+ take: 100,
+ include: {
+ exercises: {
+ orderBy: { position: "asc" },
+ include: { sets: { orderBy: { position: "asc" } } },
+ },
+ },
+ });
+}
+
+export async function createWorkout(db: PrismaClient, userId: string, input: WorkoutInput) {
+ const startedAt = checkedDate(input.startedAt);
+ const endedAt = checkedDate(input.endedAt);
+ const measured = Math.round((endedAt.getTime() - startedAt.getTime()) / 60000);
+ if (measured <= 0 || measured > 1440 || Math.abs(measured - input.durationMinutes) > 1) {
+ throw new OnboardingError(400, "Workout duration must match start and finish times.");
+ }
+ const existing = await db.workoutSession.findUnique({
+ where: { userId_requestId: { userId, requestId: input.requestId } },
+ });
+ if (existing) return { id: existing.id, replayed: true };
+ try {
+ const row = await db.workoutSession.create({
+ data: {
+ userId,
+ requestId: input.requestId,
+ title: input.title,
+ activityKey: input.activityKey,
+ startedAt,
+ endedAt,
+ durationMinutes: measured,
+ distanceMeters: input.distanceMeters,
+ notes: input.notes,
+ source: "MANUAL",
+ exercises: {
+ create: input.exercises.map((e, position) => ({
+ name: e.name,
+ position,
+ sets: { create: e.sets.map((s, index) => ({ ...s, position: index })) },
+ })),
+ },
+ },
+ select: { id: true },
+ });
+ return { id: row.id, replayed: false };
+ } catch (error) {
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "P2002") {
+ const row = await db.workoutSession.findUnique({
+ where: { userId_requestId: { userId, requestId: input.requestId } },
+ });
+ if (row) return { id: row.id, replayed: true };
+ }
+ throw error;
+ }
+}
+
+export async function removeWorkout(db: PrismaClient, userId: string, id: string) {
+ const deleted = await db.workoutSession.deleteMany({ where: { id, userId } });
+ if (!deleted.count) throw new OnboardingError(404, "Workout not found.");
+}
diff --git a/src/lib/validations/wellness.ts b/src/lib/validations/wellness.ts
new file mode 100644
index 00000000..2c5cf82f
--- /dev/null
+++ b/src/lib/validations/wellness.ts
@@ -0,0 +1,125 @@
+import { z } from "zod";
+import { ACTIVITY_KEYS } from "@/lib/personal/muscle-map";
+
+const requestId = z.uuid();
+const timestamp = z.iso.datetime({ offset: true });
+export const wellnessRemoveInput = z.object({ id: z.string().min(10).max(128) }).strict();
+
+export const goalInput = z
+ .object({
+ title: z.string().trim().min(2).max(80),
+ metric: z.enum(["WORKOUT_SESSIONS", "ACTIVITY_MINUTES", "SLEEP_MINUTES", "HYDRATION_ML"]),
+ cadence: z.enum(["WEEKLY", "TOTAL"]),
+ target: z.number().int().min(1).max(10000000),
+ endsAt: timestamp.optional(),
+ })
+ .strict();
+export const goalChangeInput = z
+ .object({
+ id: z.string().min(10).max(128),
+ title: z.string().trim().min(2).max(80).optional(),
+ target: z.number().int().min(1).max(10000000).optional(),
+ status: z.enum(["ACTIVE", "PAUSED", "ARCHIVED"]).optional(),
+ })
+ .strict()
+ .refine(
+ (v) => v.title !== undefined || v.target !== undefined || v.status !== undefined,
+ "No change specified"
+ );
+
+export const workoutInput = z
+ .object({
+ requestId,
+ title: z.string().trim().min(2).max(100),
+ activityKey: z.enum(ACTIVITY_KEYS as [string, ...string[]]),
+ startedAt: timestamp,
+ endedAt: timestamp,
+ durationMinutes: z.number().int().min(1).max(1440),
+ distanceMeters: z.number().int().min(0).max(1000000).optional(),
+ notes: z.string().trim().max(500).optional(),
+ exercises: z
+ .array(
+ z
+ .object({
+ name: z.string().trim().min(1).max(100),
+ sets: z
+ .array(
+ z
+ .object({
+ reps: z.number().int().min(0).max(1000).optional(),
+ weightGrams: z.number().int().min(0).max(1000000).optional(),
+ durationSeconds: z.number().int().min(0).max(86400).optional(),
+ distanceMeters: z.number().int().min(0).max(1000000).optional(),
+ })
+ .strict()
+ )
+ .min(1)
+ .max(30),
+ })
+ .strict()
+ )
+ .max(30)
+ .default([]),
+ })
+ .strict();
+export const sleepInput = z
+ .object({
+ requestId,
+ startedAt: timestamp,
+ endedAt: timestamp,
+ quality: z.number().int().min(1).max(5).optional(),
+ isNap: z.boolean().default(false),
+ })
+ .strict();
+export const mealInput = z
+ .object({
+ requestId,
+ mealType: z.enum(["BREAKFAST", "LUNCH", "DINNER", "SNACK"]),
+ eatenAt: timestamp,
+ notes: z.string().trim().max(300).optional(),
+ items: z
+ .array(
+ z
+ .object({
+ name: z.string().trim().min(1).max(100),
+ portionGrams: z.number().int().min(1).max(50000).optional(),
+ caloriesKcal: z.number().int().min(0).max(50000).optional(),
+ proteinGrams: z.number().int().min(0).max(10000).optional(),
+ carbsGrams: z.number().int().min(0).max(10000).optional(),
+ fatGrams: z.number().int().min(0).max(10000).optional(),
+ })
+ .strict()
+ )
+ .min(1)
+ .max(20),
+ })
+ .strict();
+export const hydrationInput = z
+ .object({
+ requestId,
+ volumeMl: z.number().int().min(1).max(5000),
+ takenAt: timestamp,
+ })
+ .strict();
+export const recoveryInput = z
+ .object({
+ localDate: z.iso.date(),
+ energy: z.number().int().min(1).max(5).optional(),
+ soreness: z.number().int().min(1).max(5).optional(),
+ stress: z.number().int().min(1).max(5).optional(),
+ satisfaction: z.number().int().min(1).max(5).optional(),
+ notes: z.string().trim().max(300).optional(),
+ })
+ .strict()
+ .refine(
+ (v) =>
+ [v.energy, v.soreness, v.stress, v.satisfaction].some((x) => x !== undefined) || !!v.notes,
+ "Add at least one check-in observation"
+ );
+
+export type GoalInput = z.infer;
+export type WorkoutInput = z.infer;
+export type SleepInput = z.infer;
+export type MealInput = z.infer;
+export type HydrationInput = z.infer;
+export type RecoveryInput = z.infer;
diff --git a/tests/integration/p1b-wellness.test.mjs b/tests/integration/p1b-wellness.test.mjs
new file mode 100644
index 00000000..261f7821
--- /dev/null
+++ b/tests/integration/p1b-wellness.test.mjs
@@ -0,0 +1,99 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { randomUUID } from "node:crypto";
+import { register } from "node:module";
+import pg from "pg";
+assert.ok(process.env.DATABASE_URL, "Run against migrated disposable PostgreSQL only");
+register("./helpers/src-alias-hook.mjs", import.meta.url);
+const { PrismaClient } = await import("../../src/generated/prisma/client.ts");
+const { PrismaPg } = await import("@prisma/adapter-pg");
+const [profile, goals, workouts, sleep, diet, recovery, insights] = await Promise.all([
+ import("../../src/lib/personal/personal-service.ts"),
+ import("../../src/lib/personal/wellness-goals.ts"),
+ import("../../src/lib/personal/wellness-workouts.ts"),
+ import("../../src/lib/personal/wellness-sleep.ts"),
+ import("../../src/lib/personal/wellness-nutrition.ts"),
+ import("../../src/lib/personal/wellness-recovery.ts"),
+ import("../../src/lib/personal/wellness-insights.ts"),
+]);
+const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
+const db = new PrismaClient({ adapter: new PrismaPg(pool) });
+test.after(() => pool.end());
+const now = new Date();
+const uid = () => randomUUID();
+const mk = async (name) =>
+ db.user.create({ data: { name, email: "wellness-" + uid() + "@example.invalid" } });
+
+test("P1-B private wellness records are isolated, idempotent, counted and erased", async () => {
+ const a = await mk("Adult A"),
+ b = await mk("Adult B");
+ try {
+ await profile.updateBio(db, a.id, { birthYear: 1990 });
+ await profile.updateBio(db, b.id, { birthYear: 1990 });
+ const g = await goals.createGoal(db, a.id, {
+ title: "Move weekly",
+ metric: "WORKOUT_SESSIONS",
+ target: 3,
+ cadence: "WEEKLY",
+ });
+ const ending = new Date(now.getTime() - 3600000);
+ const starting = new Date(ending.getTime() - 30 * 60000);
+ const requestId = uid();
+ const w = {
+ requestId,
+ title: "Run",
+ activityKey: "running",
+ startedAt: starting.toISOString(),
+ endedAt: ending.toISOString(),
+ durationMinutes: 30,
+ exercises: [],
+ };
+ const first = await workouts.createWorkout(db, a.id, w);
+ const replay = await workouts.createWorkout(db, a.id, w);
+ assert.equal(first.id, replay.id);
+ assert.equal(await db.workoutSession.count({ where: { userId: a.id } }), 1);
+ await assert.rejects(workouts.removeWorkout(db, b.id, first.id), (e) => e.status === 404);
+ await assert.rejects(
+ goals.changeGoal(db, b.id, { id: g.id, status: "ARCHIVED" }),
+ (e) => e.status === 404
+ );
+ const s = await sleep.recordSleep(db, a.id, {
+ requestId: uid(),
+ startedAt: new Date(now.getTime() - 9 * 3600000).toISOString(),
+ endedAt: new Date(now.getTime() - 3600000).toISOString(),
+ isNap: false,
+ });
+ assert.ok(s.id);
+ await diet.recordMeal(db, a.id, {
+ requestId: uid(),
+ mealType: "LUNCH",
+ eatenAt: ending.toISOString(),
+ items: [{ name: "Rice" }],
+ });
+ await diet.recordHydration(db, a.id, {
+ requestId: uid(),
+ takenAt: ending.toISOString(),
+ volumeMl: 300,
+ });
+ await recovery.saveRecovery(db, a.id, { localDate: now.toISOString().slice(0, 10), energy: 4 });
+ const view = await insights.wellnessInsights(db, a.id, now);
+ assert.equal(view.thisWeek.workouts, 1);
+ assert.equal(view.thisWeek.activityMinutes, 30);
+ assert.equal(view.goals.find((x) => x.id === g.id).achieved, 1);
+ const other = await insights.wellnessInsights(db, b.id, now);
+ assert.equal(other.thisWeek.workouts, 0);
+ assert.equal(other.goals.length, 0);
+ const exported = await profile.exportPersonalData(db, a.id);
+ assert.equal(exported.wellness.workouts.length, 1);
+ assert.equal(exported.wellness.meals.length, 1);
+ await profile.deleteAllPersonalData(db, a.id);
+ assert.equal(await db.workoutSession.count({ where: { userId: a.id } }), 0);
+ assert.equal(await db.workoutExercise.count({ where: { workoutId: first.id } }), 0);
+ assert.equal(await db.personalGoalInstance.count({ where: { userId: a.id } }), 0);
+ assert.equal(await db.mealEntry.count({ where: { userId: a.id } }), 0);
+ assert.equal(await db.recoveryCheckIn.count({ where: { userId: a.id } }), 0);
+ assert.ok(await db.user.findUnique({ where: { id: a.id } }));
+ } finally {
+ await db.user.deleteMany({ where: { id: { in: [a.id, b.id] } } });
+ }
+});
diff --git a/tests/unit/wellness-rules.test.mjs b/tests/unit/wellness-rules.test.mjs
new file mode 100644
index 00000000..b049d3f1
--- /dev/null
+++ b/tests/unit/wellness-rules.test.mjs
@@ -0,0 +1,27 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { register } from "node:module";
+register("../integration/helpers/src-alias-hook.mjs", import.meta.url);
+const { sleepMinutes, localDate, mondayUtc, safeRate } =
+ await import("../../src/lib/personal/wellness-rules.ts");
+
+test("overnight and daylight-saving timestamps use elapsed time not calendar subtraction", () => {
+ assert.equal(
+ sleepMinutes(new Date("2026-11-18T22:30:00Z"), new Date("2026-11-19T06:00:00Z")),
+ 450
+ );
+ assert.equal(
+ sleepMinutes(new Date("2026-03-08T06:00:00Z"), new Date("2026-03-08T13:00:00Z")),
+ 420
+ );
+ assert.equal(localDate(new Date("2026-11-18T20:15:00Z"), "Asia/Kolkata"), "2026-11-19");
+ assert.equal(localDate(new Date("2026-11-18T20:15:00Z"), "UTC"), "2026-11-18");
+});
+test("weekly boundary and unavailable denominator are explicit", () => {
+ assert.equal(
+ mondayUtc(new Date("2026-11-18T12:00:00Z")).toISOString(),
+ "2026-11-16T00:00:00.000Z"
+ );
+ assert.equal(safeRate(1, 3), 33);
+ assert.equal(safeRate(0, 0), null);
+});