Files
FitOS/api/prisma/schema.prisma

760 lines
24 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
enum PlanStatus {
DRAFT
ACTIVE
COMPLETED
ABANDONED
}
enum DayStatus {
PLANNED
COMPLETED
SKIPPED
}
enum SessionStatus {
IN_PROGRESS
COMPLETED
ABANDONED
}
enum GymRole {
OWNER
TRAINER
MEMBER
}
/// VIRTUAL = user-created gym mirroring a real one (public or private); REAL = physical gym.
enum GymKind {
VIRTUAL
REAL
}
/// Thumb vote on how well a virtual gym mirrors the real one.
enum GymVote {
UP
DOWN
}
/// Status of a gym claim (verification of a virtual gym or a new real gym).
enum ClaimStatus {
PENDING
APPROVED
REJECTED
}
/// Status of an invitation to a (private) virtual gym.
enum GymInvitationStatus {
PENDING
ACCEPTED
DECLINED
}
enum CoachingStatus {
PENDING
ACTIVE
DECLINED
ARCHIVED
}
enum ExerciseSource {
BUILTIN
GYM_CUSTOM
TRAINER_CUSTOM
}
/// Equipment type — determines the shape of the type-specific `spec` payload.
enum EquipmentKind {
DUMBBELL
KETTLEBELL
BARBELL
CABLE
MACHINE
BENCH
CARDIO
BODYWEIGHT
OTHER
}
/// Status konta — kara nadawana przez admina; SUSPENDED ma termin (suspensionUntil).
enum UserStatus {
ACTIVE
SUSPENDED
BANNED
}
model User {
id String @id @default(cuid())
email String @unique
passwordHash String
firstName String?
lastName String?
nickname String?
socialMedia Json?
age Int?
heightCm Float?
phone String? @unique
isAdmin Boolean @default(false)
tokenVersion Int @default(0)
status UserStatus @default(ACTIVE)
suspensionUntil DateTime?
restrictionReason String?
availability Json?
priorities String?
exclusions String?
developMuscles String[] @default([])
canDoMuscles String[] @default([])
difficultMuscles String[] @default([])
avoidMuscles String[] @default([])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
memberships GymMembership[]
plans TrainingPlan[]
createdPlans TrainingPlan[] @relation("PlanCreator")
planSharesBy PlanShare[] @relation("PlanShareBy")
planSharesWith PlanShare[] @relation("PlanShareWith")
weightEntries BodyMeasurement[]
circumferenceEntries CircumferenceMeasurement[]
coachingsAsTrainer Coaching[] @relation("CoachingTrainer")
coachingsAsUser Coaching[] @relation("CoachingUser")
commentsAsAuthor Comment[] @relation("CommentAuthor")
commentsAsTarget Comment[] @relation("CommentTarget")
messagesAsSender Message[] @relation("MessageSender")
conversationReads ConversationRead[]
activityLogs ActivityLog[] @relation("ActivityLogActor")
gymRatings GymRating[]
gymClaims GymClaim[]
claimsDecided GymClaim[] @relation("ClaimDecider")
gymInvitations GymInvitation[]
gymInvitationsSent GymInvitation[] @relation("GymInviteSender")
notifications Notification[]
announcementsAuthored Announcement[] @relation("AnnouncementAuthor")
announcementReads AnnouncementRead[]
}
/// Audit trail of user actions (app + trainer level). Best-effort writes,
/// read-only for admins (GET /admin/logs).
model ActivityLog {
id String @id @default(cuid())
actorId String
action String
entityType String
entityId String?
details Json?
createdAt DateTime @default(now())
actor User @relation("ActivityLogActor", fields: [actorId], references: [id], onDelete: Cascade)
@@index([createdAt])
@@index([actorId, createdAt])
@@index([action])
}
/// Trainer ↔ trainee relation. Created as PENDING (invitation), becomes ACTIVE
/// after the invited party accepts. Invitations expire after 7 days.
model Coaching {
id String @id @default(cuid())
trainerId String
userId String
gymId String?
status CoachingStatus @default(PENDING)
note String?
invitedBy String
invitedAt DateTime @default(now())
expiresAt DateTime
createdAt DateTime @default(now())
trainer User @relation("CoachingTrainer", fields: [trainerId], references: [id], onDelete: Cascade)
user User @relation("CoachingUser", fields: [userId], references: [id], onDelete: Cascade)
messages Message[]
@@unique([trainerId, userId])
@@index([trainerId, status])
@@index([userId, status])
}
/// Async comment (trainer or user) about a trainee, optionally anchored to a session
/// or to a specific exercise within the session.
model Comment {
id String @id @default(cuid())
authorId String
targetUserId String
sessionId String?
sessionExerciseId String?
body String
createdAt DateTime @default(now())
author User @relation("CommentAuthor", fields: [authorId], references: [id], onDelete: Cascade)
target User @relation("CommentTarget", fields: [targetUserId], references: [id], onDelete: Cascade)
sessionExercise SessionExercise? @relation(fields: [sessionExerciseId], references: [id], onDelete: SetNull)
@@index([targetUserId, createdAt])
}
/// Wiadomość w wątku trener↔podopieczny (per Coaching).
model Message {
id String @id @default(cuid())
coachingId String
senderId String
body String
sessionId String?
sessionExerciseId String?
createdAt DateTime @default(now())
coaching Coaching @relation(fields: [coachingId], references: [id], onDelete: Cascade)
sender User @relation("MessageSender", fields: [senderId], references: [id], onDelete: Cascade)
session TrainingSession? @relation("MessageSession", fields: [sessionId], references: [id], onDelete: SetNull)
sessionExercise SessionExercise? @relation("MessageSessionExercise", fields: [sessionExerciseId], references: [id], onDelete: SetNull)
@@index([coachingId, createdAt])
}
/// Oznaczenie przeczytania wątku per strona relacji (do licznika nieprzeczytanych).
model ConversationRead {
coachingId String
userId String
lastReadAt DateTime
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([coachingId, userId])
}
/// Rodzaj osobistego powiadomienia (warstwa systemowa feedu „Aktualności").
enum NotificationType {
PLAN_READY
PLAN_SHARED
GYM_DELETED
}
/// Osobiste powiadomienie generowane przez system. `payload` jest self-contained
/// (np. nazwa siłowni przy GYM_DELETED) — przeżywa usunięcie encji źródłowej.
model Notification {
id String @id @default(cuid())
userId String
type NotificationType
/// Gotowy tekst PL wygenerowany przy tworzeniu (renderowany 1:1 w UI).
title String
/// Dane do deeplinków: { planId?, planTitle?, gymName?, sharedBy?, ... }.
payload Json
readAt DateTime?
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId, readAt])
@@index([userId, createdAt])
}
/// Rodzaj ogłoszenia — MANUAL pisane przez osobę, pozostałe generowane systemowo.
enum AnnouncementKind {
MANUAL
HOURS_CHANGE
EXCEPTION
}
/// Ogłoszenie broadcastowe: do członków siłowni (gymId) albo globalne (gymId = null).
/// NIE mnożone per odbiorca — stan przeczytania w AnnouncementRead.
model Announcement {
id String @id @default(cuid())
/// null = ogłoszenie globalne platformy (autor = admin).
gymId String?
/// Autor (OWNER siłowni / admin); null = wygenerowane systemowo.
authorId String?
kind AnnouncementKind @default(MANUAL)
title String
body String
createdAt DateTime @default(now())
gym Gym? @relation(fields: [gymId], references: [id], onDelete: Cascade)
author User? @relation("AnnouncementAuthor", fields: [authorId], references: [id], onDelete: SetNull)
reads AnnouncementRead[]
@@index([gymId, createdAt])
@@index([createdAt])
}
/// Oznaczenie przeczytania ogłoszenia per user (do licznika nieprzeczytanych).
model AnnouncementRead {
announcementId String
userId String
readAt DateTime @default(now())
announcement Announcement @relation(fields: [announcementId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([announcementId, userId])
@@index([userId])
}
model Gym {
id String @id @default(cuid())
name String
/// Display string wyliczany z adresu (fallback dla starszych, swobodnych lokalizacji).
location String?
/// Strukturyzowany adres (wzorzec Google/UPU) — `location` składa się z tych pol.
addressLine1 String?
addressLine2 String?
postalCode String?
city String?
/// ISO 3166-1 alpha-2; default PL, przy innym kraju dopisywany do display-stringa.
countryCode String? @default("PL")
availability Json?
capacity Int?
/// Existing rows default to REAL; VIRTUAL gyms are created by users.
kind GymKind @default(REAL)
/// Only meaningful for VIRTUAL gyms (hidden from the public list).
isPrivate Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
memberships GymMembership[]
customExercises Exercise[]
equipment GymEquipment[]
exceptions GymException[]
ratings GymRating[]
claims GymClaim[]
invitations GymInvitation[]
photos GymPhoto[]
plans TrainingPlan[]
announcements Announcement[]
}
/// Zdjęcie w galerii siłowni REAL. `order` = kolejność; okładka = najmniejsze `order` (tie → najstarsze `createdAt`).
model GymPhoto {
id String @id @default(cuid())
gymId String
storedName String
mimeType String
sizeBytes Int
order Int @default(0)
createdAt DateTime @default(now())
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
@@index([gymId, order])
}
/// One thumb vote per user on a PUBLIC virtual gym (how well it mirrors the real one).
model GymRating {
id String @id @default(cuid())
gymId String
userId String
vote GymVote
createdAt DateTime @default(now())
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([gymId, userId])
@@index([gymId])
}
/// A claim: verification of an existing virtual gym (gymId set) or a request for a
/// new real gym (gymId null, gym data carried in the claim).
model GymClaim {
id String @id @default(cuid())
/// null = claim for a NEW real gym (data below); set = verification of that virtual gym.
gymId String?
userId String
/// Gym data — only for claims with gymId = null:
gymName String?
gymLocation String?
gymAvailability Json?
gymCapacity Int?
/// Applicant data / proof:
description String
companyName String?
nip String?
phone String?
email String?
/// Verification claims only: overrides gym.location on approval.
address String?
status ClaimStatus @default(PENDING)
rejectReason String?
decidedById String?
decidedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
gym Gym? @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
decidedBy User? @relation("ClaimDecider", fields: [decidedById], references: [id], onDelete: SetNull)
documents GymClaimDocument[]
@@index([gymId, status])
@@index([userId, status])
@@index([status])
}
/// Uploaded proof document attached to a gym claim.
model GymClaimDocument {
id String @id @default(cuid())
claimId String
originalName String
storedName String
mimeType String
sizeBytes Int
createdAt DateTime @default(now())
claim GymClaim @relation(fields: [claimId], references: [id], onDelete: Cascade)
}
/// Invitation to a PRIVATE virtual gym (owner invites a specific user, 7-day TTL).
model GymInvitation {
id String @id @default(cuid())
gymId String
userId String
invitedById String
status GymInvitationStatus @default(PENDING)
invitedAt DateTime @default(now())
expiresAt DateTime
createdAt DateTime @default(now())
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
invitedBy User @relation("GymInviteSender", fields: [invitedById], references: [id], onDelete: Cascade)
// No hard unique — a re-invite after DECLINED updates the existing row.
@@index([gymId, userId])
@@index([userId, status])
@@index([invitedById, status])
}
/// Gym ↔ equipment instance: a concrete set of units of a catalog type the gym owns
/// (e.g. four fixed 5 kg dumbbells AND two adjustable 2–24 kg dumbbells = two instances).
/// `spec` overrides the catalog spec for this instance (validated against the catalog
/// item's `kind`); null = inherit the catalog spec.
model GymEquipment {
id String @id @default(cuid())
gymId String
equipmentId String
quantity Int @default(1)
spec Json?
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
equipment Equipment @relation(fields: [equipmentId], references: [id], onDelete: Cascade)
photos EquipmentPhoto[]
@@index([gymId, equipmentId])
}
/// Photo of a gym's equipment instance (stored under UPLOAD_DIR/gyms/<gymId>/equipment/<instanceId>/).
model EquipmentPhoto {
id String @id @default(cuid())
gymEquipmentId String
storedName String
mimeType String
sizeBytes Int
createdAt DateTime @default(now())
gymEquipment GymEquipment @relation(fields: [gymEquipmentId], references: [id], onDelete: Cascade)
@@index([gymEquipmentId, createdAt])
}
/// One-off override for a specific date (null = closed, { start, end } = different hours).
/// Automatically removed by the scheduler once the date is in the past.
model GymException {
id String @id @default(cuid())
gymId String
date DateTime
availability Json?
createdAt DateTime @default(now())
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
@@unique([gymId, date])
@@index([date])
}
model FocusArea {
id String @id @default(cuid())
name String @unique
nameEn String?
muscle String @unique
description String?
/// Recommended weekly volume range in sets (decision 13 — volume warning).
setsMin Int?
setsMax Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model GymMembership {
id String @id @default(cuid())
userId String
gymId String
roles GymRole[] @default([MEMBER])
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
gym Gym @relation(fields: [gymId], references: [id], onDelete: Cascade)
@@unique([userId, gymId])
}
model BodyMeasurement {
id String @id @default(cuid())
userId String
value Float
date DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId, date])
}
model CircumferenceMeasurement {
id String @id @default(cuid())
userId String
/// Identyfikator typu pomiaru z listy (chest/waist/...); null dla starszych pomiarów zapisanych jako swobodna nazwa.
typeId String?
/// Strona pomiaru w parach (left/right); null dla pomiarów niesymetrycznych i starszych.
side String?
/// Etykieta seryjna: null dla nowych pomiarów (etykieta wynika z typeId+side), zachowana dla starszych.
name String?
value Float
date DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([userId, date])
}
/// Gym machine/device catalog entry (e.g. Sztanga, Hantle, Wyciąg).
/// Linked to exercise types (which machines an exercise uses) and gyms (which machines a gym has).
/// `kind` determines the shape of the type-specific `spec` payload:
/// DUMBBELL/KETTLEBELL/CABLE/MACHINE → { minKg, maxKg } (available load range)
/// BARBELL/BENCH → { maxLoadKg } (max total load)
/// CARDIO → { maxSpeedKmh?, maxInclinePct? }
/// BODYWEIGHT/OTHER → no spec
model Equipment {
id String @id @default(cuid())
name String @unique
nameEn String?
kind EquipmentKind @default(OTHER)
spec Json?
description String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
exercises Exercise[]
gyms GymEquipment[]
}
model Exercise {
id String @id @default(cuid())
slug String @unique
name String
nameEn String?
primaryMuscle String
secondaryMuscles String[]
hasReps Boolean @default(true)
hasLoad Boolean @default(true)
hasRest Boolean @default(true)
hasSets Boolean @default(true)
hasRir Boolean @default(true)
hasDifficulty Boolean @default(true)
hasCardio Boolean @default(false)
hasTime Boolean @default(false)
hasSpeed Boolean @default(false)
description String?
howTo String?
commonMistakes String?
source ExerciseSource @default(BUILTIN)
gymId String?
trainerId String?
seedVersion Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
gym Gym? @relation(fields: [gymId], references: [id], onDelete: SetNull)
equipment Equipment[]
planExercises PlanExercise[]
sessionExercises SessionExercise[]
@@index([source])
}
model TrainingPlan {
/// Inwariant: jeden aktywny plan na użytkownika pilnuje częściowy indeks
/// unikalny `TrainingPlan_userId_active_key` ("userId") WHERE status='ACTIVE'
/// — utworzony w migracji 20260904120000 (Prisma nie wspiera indeksów
/// częściowych w schemacie, patrz README „Kluczowe decyzje (MVP)”).
id String @id @default(cuid())
title String
userId String
creatorId String?
status PlanStatus @default(DRAFT)
weeksCount Int
startDate DateTime?
/// Informacyjna — siłownia, w której realizowany jest plan (bez wpływu na scheduler).
gymId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
creator User? @relation("PlanCreator", fields: [creatorId], references: [id], onDelete: SetNull)
gym Gym? @relation(fields: [gymId], references: [id], onDelete: SetNull)
weeks PlanWeek[]
shares PlanShare[]
@@index([userId, status])
@@index([gymId])
}
/// Explicit plan sharing (trainer <-> trainee): the owner shares a plan with a user
/// in an ACTIVE coaching relation. Recipients get read-only access.
model PlanShare {
id String @id @default(cuid())
planId String
sharedById String
sharedWithId String
createdAt DateTime @default(now())
plan TrainingPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
sharedBy User @relation("PlanShareBy", fields: [sharedById], references: [id], onDelete: Cascade)
sharedWith User @relation("PlanShareWith", fields: [sharedWithId], references: [id], onDelete: Cascade)
@@unique([planId, sharedWithId])
@@index([sharedWithId])
}
model PlanWeek {
id String @id @default(cuid())
planId String
index Int
/// Opcjonalny alias tygodnia (np. „Deload").
customName String?
plan TrainingPlan @relation(fields: [planId], references: [id], onDelete: Cascade)
days PlanDay[]
@@unique([planId, index])
}
model PlanDay {
id String @id @default(cuid())
weekId String
dayOfWeek Int
date DateTime?
status DayStatus @default(PLANNED)
completedAt DateTime?
skippedAt DateTime?
week PlanWeek @relation(fields: [weekId], references: [id], onDelete: Cascade)
moveLog DayMove[]
exercises PlanExercise[]
sessions TrainingSession[]
@@index([date, status])
}
model DayMove {
id String @id @default(cuid())
dayId String
fromDate DateTime
toDate DateTime
reason String?
movedAt DateTime @default(now())
day PlanDay @relation(fields: [dayId], references: [id], onDelete: Cascade)
}
model PlanExercise {
id String @id @default(cuid())
dayId String
exerciseId String
order Int
day PlanDay @relation(fields: [dayId], references: [id], onDelete: Cascade)
exercise Exercise @relation(fields: [exerciseId], references: [id])
sets PlanSet[]
sessionExercises SessionExercise[]
@@unique([dayId, order])
}
model PlanSet {
id String @id @default(cuid())
exerciseId String
index Int
reps Int?
loadKg Float?
restSec Int?
rir Int?
cardioBpm Int?
timeSec Int?
speed Float?
exercise PlanExercise @relation(fields: [exerciseId], references: [id], onDelete: Cascade)
sessionSets SessionSet[]
@@unique([exerciseId, index])
}
model TrainingSession {
/// Inwariant: jedna aktywna sesja na dzień pilnuje częściowy indeks unikalny
/// `TrainingSession_dayId_in_progress_key` ("dayId") WHERE status='IN_PROGRESS'
/// — utworzony w migracji 20261011000000 (Prisma nie wspiera indeksów
/// częściowych w schemacie).
id String @id @default(cuid())
dayId String
status SessionStatus @default(IN_PROGRESS)
startedAt DateTime @default(now())
endedAt DateTime?
day PlanDay @relation(fields: [dayId], references: [id], onDelete: Cascade)
exercises SessionExercise[]
messagesAsSession Message[] @relation("MessageSession")
@@index([dayId, status])
}
model SessionExercise {
id String @id @default(cuid())
sessionId String
exerciseId String
planExerciseId String?
order Int
hidden Boolean @default(false)
removed Boolean @default(false)
session TrainingSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)
exercise Exercise @relation(fields: [exerciseId], references: [id])
planExercise PlanExercise? @relation(fields: [planExerciseId], references: [id], onDelete: SetNull)
sets SessionSet[]
comments Comment[]
messagesAsExercise Message[] @relation("MessageSessionExercise")
@@unique([sessionId, order])
}
model SessionSet {
id String @id @default(cuid())
exerciseId String
planSetId String?
index Int
reps Int?
rir Int?
difficulty Int?
note String?
removed Boolean @default(false)
exercise SessionExercise @relation(fields: [exerciseId], references: [id], onDelete: Cascade)
planSet PlanSet? @relation(fields: [planSetId], references: [id])
@@unique([exerciseId, index])
}