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 ( + <> +
+

Rest journal

+

Sleep

+
+ +
+

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 ( +
+

Set a personal goal

+

+ Only completed sessions and logged observations count toward your goal. +

+ +
+ + + +
+ + {message && ( + + {message} + + )} +
+ ); +} + +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 ( +
+

Food journal

+

+ Write one food per line. Optionally add | grams | calories | protein grams. Unknown + nutrients stay unknown, never zero. +

+ +