Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 2 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions docs/P1B_WELLNESS_ENGINE.md
Original file line number Diff line number Diff line change
@@ -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.
116 changes: 116 additions & 0 deletions prisma/migrations/20261118190000_p1b_wellness_engine/migration.sql
Original file line number Diff line number Diff line change
@@ -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");
182 changes: 182 additions & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions src/app/api/me/wellness/goals/change/route.ts
Original file line number Diff line number Diff line change
@@ -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)
);
}
10 changes: 10 additions & 0 deletions src/app/api/me/wellness/goals/remove/route.ts
Original file line number Diff line number Diff line change
@@ -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)
);
}
13 changes: 13 additions & 0 deletions src/app/api/me/wellness/goals/route.ts
Original file line number Diff line number Diff line change
@@ -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)
);
}
Loading
Loading