From e9edfff631e562a8b9e677df15f18da12b5073dc Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 09:57:50 +0530 Subject: [PATCH 1/8] feat(personal): add isolated adult wellness schema and rollout policy --- .../migration.sql | 116 +++++++++++ prisma/schema.prisma | 182 ++++++++++++++++++ src/lib/personal/wellness-policy.ts | 28 +++ 3 files changed, 326 insertions(+) create mode 100644 prisma/migrations/20261118190000_p1b_wellness_engine/migration.sql create mode 100644 src/lib/personal/wellness-policy.ts 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..49b64726 --- /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 +); +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 +); +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 +); +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 +); +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 +); +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 +); +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 +); +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 +); +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 +); +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 +); +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/lib/personal/wellness-policy.ts b/src/lib/personal/wellness-policy.ts new file mode 100644 index 00000000..35668bcb --- /dev/null +++ b/src/lib/personal/wellness-policy.ts @@ -0,0 +1,28 @@ +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; +} From 0d096ac02e50172735af821afff472ada7d37157 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 09:57:54 +0530 Subject: [PATCH 2/8] feat(personal): add verified wellness API contracts, validation and metrics primitives --- src/lib/personal/wellness-http.ts | 43 +++++++++++++++++ src/lib/personal/wellness-page.ts | 12 +++++ src/lib/personal/wellness-rules.ts | 23 +++++++++ src/lib/validations/wellness.ts | 76 ++++++++++++++++++++++++++++++ 4 files changed, 154 insertions(+) create mode 100644 src/lib/personal/wellness-http.ts create mode 100644 src/lib/personal/wellness-page.ts create mode 100644 src/lib/personal/wellness-rules.ts create mode 100644 src/lib/validations/wellness.ts diff --git a/src/lib/personal/wellness-http.ts b/src/lib/personal/wellness-http.ts new file mode 100644 index 00000000..d24f2b56 --- /dev/null +++ b/src/lib/personal/wellness-http.ts @@ -0,0 +1,43 @@ +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-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-rules.ts b/src/lib/personal/wellness-rules.ts new file mode 100644 index 00000000..647043c1 --- /dev/null +++ b/src/lib/personal/wellness-rules.ts @@ -0,0 +1,23 @@ +/** 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/validations/wellness.ts b/src/lib/validations/wellness.ts new file mode 100644 index 00000000..77da446d --- /dev/null +++ b/src/lib/validations/wellness.ts @@ -0,0 +1,76 @@ +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; From 64c0d1b0684cd195d234f0933831960faae73350 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 09:58:07 +0530 Subject: [PATCH 3/8] feat(personal): user-owned goal lifecycle, protected API and HM2 goal UI --- src/app/api/me/wellness/goals/change/route.ts | 9 +++ src/app/api/me/wellness/goals/remove/route.ts | 9 +++ src/app/api/me/wellness/goals/route.ts | 12 ++++ src/app/me/goals/loading.tsx | 1 + src/app/me/goals/page.tsx | 22 ++++++ src/components/personal/wellness-goals.tsx | 67 +++++++++++++++++++ src/lib/personal/wellness-goals.ts | 39 +++++++++++ 7 files changed, 159 insertions(+) create mode 100644 src/app/api/me/wellness/goals/change/route.ts create mode 100644 src/app/api/me/wellness/goals/remove/route.ts create mode 100644 src/app/api/me/wellness/goals/route.ts create mode 100644 src/app/me/goals/loading.tsx create mode 100644 src/app/me/goals/page.tsx create mode 100644 src/components/personal/wellness-goals.tsx create mode 100644 src/lib/personal/wellness-goals.ts 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..ae0d7e10 --- /dev/null +++ b/src/app/api/me/wellness/goals/change/route.ts @@ -0,0 +1,9 @@ +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..2613d0ec --- /dev/null +++ b/src/app/api/me/wellness/goals/remove/route.ts @@ -0,0 +1,9 @@ +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..6353330a --- /dev/null +++ b/src/app/api/me/wellness/goals/route.ts @@ -0,0 +1,12 @@ +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/me/goals/loading.tsx b/src/app/me/goals/loading.tsx new file mode 100644 index 00000000..f0db958e --- /dev/null +++ b/src/app/me/goals/loading.tsx @@ -0,0 +1 @@ +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..2ea8b13e --- /dev/null +++ b/src/app/me/goals/page.tsx @@ -0,0 +1,22 @@ +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 haven't 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/components/personal/wellness-goals.tsx b/src/components/personal/wellness-goals.tsx new file mode 100644 index 00000000..2d279626 --- /dev/null +++ b/src/components/personal/wellness-goals.tsx @@ -0,0 +1,67 @@ +"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/lib/personal/wellness-goals.ts b/src/lib/personal/wellness-goals.ts new file mode 100644 index 00000000..2bd88194 --- /dev/null +++ b/src/lib/personal/wellness-goals.ts @@ -0,0 +1,39 @@ +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."); +} From c3413c6b5fc9f6ae8a1d9f18306a228ed4a9cf65 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 09:58:12 +0530 Subject: [PATCH 4/8] feat(personal): record completed workouts and strength sets with retry-safe ownership --- .../api/me/wellness/workouts/remove/route.ts | 8 +++ src/app/api/me/wellness/workouts/route.ts | 12 ++++ src/app/me/workouts/[id]/loading.tsx | 1 + src/app/me/workouts/[id]/page.tsx | 21 ++++++ src/app/me/workouts/loading.tsx | 1 + src/app/me/workouts/page.tsx | 25 +++++++ src/components/personal/wellness-workouts.tsx | 65 +++++++++++++++++++ src/lib/personal/wellness-workouts.ts | 48 ++++++++++++++ 8 files changed, 181 insertions(+) create mode 100644 src/app/api/me/wellness/workouts/remove/route.ts create mode 100644 src/app/api/me/wellness/workouts/route.ts create mode 100644 src/app/me/workouts/[id]/loading.tsx create mode 100644 src/app/me/workouts/[id]/page.tsx create mode 100644 src/app/me/workouts/loading.tsx create mode 100644 src/app/me/workouts/page.tsx create mode 100644 src/components/personal/wellness-workouts.tsx create mode 100644 src/lib/personal/wellness-workouts.ts 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..f26aee2f --- /dev/null +++ b/src/app/api/me/wellness/workouts/remove/route.ts @@ -0,0 +1,8 @@ +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..24867bbf --- /dev/null +++ b/src/app/api/me/wellness/workouts/route.ts @@ -0,0 +1,12 @@ +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/workouts/[id]/loading.tsx b/src/app/me/workouts/[id]/loading.tsx new file mode 100644 index 00000000..1d6727e1 --- /dev/null +++ b/src/app/me/workouts/[id]/loading.tsx @@ -0,0 +1 @@ +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..769e0c88 --- /dev/null +++ b/src/app/me/workouts/[id]/page.tsx @@ -0,0 +1,21 @@ +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..b9a2a4b8 --- /dev/null +++ b/src/app/me/workouts/loading.tsx @@ -0,0 +1 @@ +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..e1d117a6 --- /dev/null +++ b/src/app/me/workouts/page.tsx @@ -0,0 +1,25 @@ +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/wellness-workouts.tsx b/src/components/personal/wellness-workouts.tsx new file mode 100644 index 00000000..5421a248 --- /dev/null +++ b/src/components/personal/wellness-workouts.tsx @@ -0,0 +1,65 @@ +"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
+

Log a completed workout

+

Actual completed sessions count toward goals. Activities you simply select in your profile do not.

+ +
+ + +
+
Optional strength details + +
+ + +
+
+
+ {message && {message}}
+
; +} +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/wellness-workouts.ts b/src/lib/personal/wellness-workouts.ts new file mode 100644 index 00000000..a7958943 --- /dev/null +++ b/src/lib/personal/wellness-workouts.ts @@ -0,0 +1,48 @@ +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."); +} From 4c10f1d27a78cb9141979715175a7c0977553bbc Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 09:58:15 +0530 Subject: [PATCH 5/8] feat(personal): journal sleep with time-safe duration and personal privacy --- src/app/api/me/wellness/sleep/remove/route.ts | 8 +++ src/app/api/me/wellness/sleep/route.ts | 11 ++++ src/app/me/sleep/loading.tsx | 1 + src/app/me/sleep/page.tsx | 22 +++++++ src/components/personal/wellness-sleep.tsx | 57 +++++++++++++++++++ src/lib/personal/wellness-sleep.ts | 39 +++++++++++++ 6 files changed, 138 insertions(+) create mode 100644 src/app/api/me/wellness/sleep/remove/route.ts create mode 100644 src/app/api/me/wellness/sleep/route.ts create mode 100644 src/app/me/sleep/loading.tsx create mode 100644 src/app/me/sleep/page.tsx create mode 100644 src/components/personal/wellness-sleep.tsx create mode 100644 src/lib/personal/wellness-sleep.ts 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..458d8e0d --- /dev/null +++ b/src/app/api/me/wellness/sleep/remove/route.ts @@ -0,0 +1,8 @@ +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..2de37c35 --- /dev/null +++ b/src/app/api/me/wellness/sleep/route.ts @@ -0,0 +1,11 @@ +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/me/sleep/loading.tsx b/src/app/me/sleep/loading.tsx new file mode 100644 index 00000000..dd58919e --- /dev/null +++ b/src/app/me/sleep/loading.tsx @@ -0,0 +1 @@ +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..cb878307 --- /dev/null +++ b/src/app/me/sleep/page.tsx @@ -0,0 +1,22 @@ +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/components/personal/wellness-sleep.tsx b/src/components/personal/wellness-sleep.tsx new file mode 100644 index 00000000..017dc2e2 --- /dev/null +++ b/src/components/personal/wellness-sleep.tsx @@ -0,0 +1,57 @@ +"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
+

Add sleep

+

Manual sleep journal. Duration is calculated from the selected times, including overnight.

+
+ + + +
+ +
+ {message && {message}}
+
; +} + +export function RemoveSleep({ id }: { id: string }) { + const router = useRouter(); + const [pending, start] = useTransition(); + const [message, setMessage] = useState(""); + return
+ + {message && {message}} +
; +} diff --git a/src/lib/personal/wellness-sleep.ts b/src/lib/personal/wellness-sleep.ts new file mode 100644 index 00000000..cebbf73f --- /dev/null +++ b/src/lib/personal/wellness-sleep.ts @@ -0,0 +1,39 @@ +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."); +} From 13d64efaf889f14c80efe8cf5d2188b5022dbc35 Mon Sep 17 00:00:00 2001 From: "Sameer .I. Siddiqui" Date: Thu, 19 Nov 2026 09:58:30 +0530 Subject: [PATCH 6/8] feat(personal): build private meal, optional nutrient and hydration journal --- .../api/me/wellness/hydration/remove/route.ts | 5 ++ src/app/api/me/wellness/hydration/route.ts | 6 ++ src/app/api/me/wellness/meals/remove/route.ts | 5 ++ src/app/api/me/wellness/meals/route.ts | 6 ++ src/app/me/nutrition/loading.tsx | 1 + src/app/me/nutrition/page.tsx | 29 +++++++ .../personal/wellness-nutrition.tsx | 78 +++++++++++++++++++ src/lib/personal/wellness-nutrition.ts | 64 +++++++++++++++ 8 files changed, 194 insertions(+) create mode 100644 src/app/api/me/wellness/hydration/remove/route.ts create mode 100644 src/app/api/me/wellness/hydration/route.ts create mode 100644 src/app/api/me/wellness/meals/remove/route.ts create mode 100644 src/app/api/me/wellness/meals/route.ts create mode 100644 src/app/me/nutrition/loading.tsx create mode 100644 src/app/me/nutrition/page.tsx create mode 100644 src/components/personal/wellness-nutrition.tsx create mode 100644 src/lib/personal/wellness-nutrition.ts 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..3f951968 --- /dev/null +++ b/src/app/api/me/wellness/hydration/remove/route.ts @@ -0,0 +1,5 @@ +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..171b0c5f --- /dev/null +++ b/src/app/api/me/wellness/hydration/route.ts @@ -0,0 +1,6 @@ +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/meals/remove/route.ts b/src/app/api/me/wellness/meals/remove/route.ts new file mode 100644 index 00000000..72731734 --- /dev/null +++ b/src/app/api/me/wellness/meals/remove/route.ts @@ -0,0 +1,5 @@ +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..7904868e --- /dev/null +++ b/src/app/api/me/wellness/meals/route.ts @@ -0,0 +1,6 @@ +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/me/nutrition/loading.tsx b/src/app/me/nutrition/loading.tsx new file mode 100644 index 00000000..003c5522 --- /dev/null +++ b/src/app/me/nutrition/loading.tsx @@ -0,0 +1 @@ +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..82de12ec --- /dev/null +++ b/src/app/me/nutrition/page.tsx @@ -0,0 +1,29 @@ +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/components/personal/wellness-nutrition.tsx b/src/components/personal/wellness-nutrition.tsx new file mode 100644 index 00000000..01c5e3b5 --- /dev/null +++ b/src/components/personal/wellness-nutrition.tsx @@ -0,0 +1,78 @@ +"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.

+ +