Baseline: stan przed refaktoryzacja struktury

This commit is contained in:
tisachi
2026-09-04 19:06:19 +02:00
commit 1c8594ad96
369 changed files with 71407 additions and 0 deletions

75
api/src/app.ts Normal file
View File

@@ -0,0 +1,75 @@
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import cookieParser from 'cookie-parser';
import { pinoHttp } from 'pino-http';
import swaggerUi from 'swagger-ui-express';
import type { AppDeps } from './deps.js';
import { config } from './config.js';
import { logger } from './lib/logger.js';
import { apiLimiter } from './middleware/rateLimit.js';
import { errorHandler, notFoundHandler } from './middleware/errorHandler.js';
import { openapi } from './swagger.js';
import { createAuthRoutes } from './routes/auth.js';
import { createMeRoutes } from './routes/me.js';
import { createExercisePoolRoutes } from './routes/exercisePool.js';
import { createFocusAreaRoutes } from './routes/focusAreas.js';
import { createGymRoutes } from './routes/gyms.js';
import { createPlanRoutes } from './routes/plans.js';
import { createSessionRoutes } from './routes/sessions.js';
import { createDashboardRoutes } from './routes/dashboard.js';
import { createCalendarRoutes } from './routes/calendar.js';
import { createTrainerRoutes } from './routes/trainer.js';
import { createMessageRoutes } from './routes/messages.js';
import { createAdminRoutes } from './routes/admin.js';
import { createEquipmentRoutes } from './routes/equipment.js';
import { createEquipmentPublicRoutes } from './routes/equipmentPublic.js';
import { createExerciseRoutes } from './routes/exercises.js';
export function createApp(deps: AppDeps): express.Express {
const app = express();
app.use(helmet());
app.use(
cors({
origin: (origin, cb) => {
if (!origin || config.corsOriginPatterns.some((re) => re.test(origin))) {
return cb(null, true);
}
return cb(new Error('Not allowed by CORS'));
},
credentials: true,
}),
);
app.use(express.json());
app.use(cookieParser());
app.use(pinoHttp({ logger, autoLogging: { ignore: (req) => req.url === '/health' } }));
app.get('/health', (_req, res) => {
res.json({ status: 'ok', uptime: process.uptime() });
});
app.use('/api/v1', deps.apiLimiter ?? apiLimiter);
app.use('/api/v1/auth', createAuthRoutes(deps));
app.use('/api/v1/me', createMeRoutes(deps));
app.use('/api/v1/exercises', createExercisePoolRoutes(deps));
app.use('/api/v1/focus-areas', createFocusAreaRoutes(deps));
app.use('/api/v1/gyms', createGymRoutes(deps));
app.use('/api/v1/equipment', createEquipmentPublicRoutes(deps));
app.use('/api/v1/plans', createPlanRoutes(deps));
app.use('/api/v1', createSessionRoutes(deps));
app.use('/api/v1/dashboard', createDashboardRoutes(deps));
app.use('/api/v1/calendar', createCalendarRoutes(deps));
app.use('/api/v1/trainer', createTrainerRoutes(deps));
app.use('/api/v1/messages', createMessageRoutes(deps));
app.use('/api/v1/admin', createAdminRoutes(deps));
app.use('/api/v1/admin/equipment', createEquipmentRoutes(deps));
app.use('/api/v1/admin/exercises', createExerciseRoutes(deps));
app.use('/api/docs', swaggerUi.serve, swaggerUi.setup(openapi));
app.use(notFoundHandler);
app.use(errorHandler);
return app;
}

27
api/src/config.ts Normal file
View File

@@ -0,0 +1,27 @@
import 'dotenv/config';
import path from 'node:path';
export const config = {
port: parseInt(process.env.PORT || '9002', 10),
nodeEnv: process.env.NODE_ENV || 'development',
databaseUrl: process.env.DATABASE_URL || 'postgresql://fitos:fitos@localhost:5432/fitos',
jwt: {
accessSecret: process.env.JWT_ACCESS_SECRET || 'dev-access-secret',
refreshSecret: process.env.JWT_REFRESH_SECRET || 'dev-refresh-secret',
accessTtlSec: 15 * 60,
refreshTtlSec: 7 * 24 * 3600,
},
firstAdminEmail: process.env.FITOS_FIRST_ADMIN_EMAIL,
firstAdminPassword: process.env.FITOS_FIRST_ADMIN_PASSWORD || 'ChangeMe123!',
logLevel: process.env.LOG_LEVEL || 'info',
uploadDir: process.env.UPLOAD_DIR || path.join(process.cwd(), 'uploads'),
// true only when served over HTTPS — over plain HTTP browsers drop Secure cookies (breaks refresh)
cookieSecure: process.env.COOKIE_SECURE === 'true',
corsOriginPatterns: [
/^https?:\/\/(www\.)?domena\.pl(:\d+)?$/,
/^https?:\/\/admin\.domena\.pl(:\d+)?$/,
/^https?:\/\/(www\.)?tisachi\.ddns\.net(:\d+)?$/,
/^https?:\/\/localhost(:\d+)?$/,
/^https?:\/\/127\.0\.0\.1(:\d+)?$/,
],
};

415
api/src/data/exercises.ts Normal file
View File

@@ -0,0 +1,415 @@
export interface ExerciseSeed {
slug: string;
name: string;
primaryMuscle: string;
secondaryMuscles: string[];
equipment: string[];
hasReps: boolean;
hasLoad: boolean;
hasRest: boolean;
hasSets: boolean;
hasRir: boolean;
hasDifficulty: boolean;
hasCardio: boolean;
hasTime: boolean;
hasSpeed: boolean;
description: string;
howTo: string;
commonMistakes: string;
difficulty: number;
}
export const SEED_VERSION = 1;
export const EXERCISES: ExerciseSeed[] = [
{
slug: 'bench-press',
name: 'Wyciskanie sztangi leżąc',
primaryMuscle: 'chest',
secondaryMuscles: ['triceps', 'shoulders'],
equipment: ['barbell'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Podstawowe ćwiczenie siłowe na klatkę piersiową.',
howTo: 'Leżąc na ławce, zjedz sztangę, opuść ją do klatki i wyciśnij w górze.',
commonMistakes: 'Brak napięcia łopatek, odbijanie sztangi od klatki, zbyt szeroki chwyt.',
difficulty: 4,
},
{
slug: 'incline-dumbbell-press',
name: 'Wyciskanie hantli skośne',
primaryMuscle: 'chest',
secondaryMuscles: ['shoulders', 'triceps'],
equipment: ['dumbbells'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wyciskanie hantli na ławce skośnej — górna część klatki.',
howTo: 'Ławka 30–45°, hantle nad klatką, wyciskanie w górę i na zewnątrz.',
commonMistakes: 'Zbyt stroma ławka (przenosi obciążenie na barki), zginanie łokci pod 90°.',
difficulty: 3,
},
{
slug: 'push-ups',
name: 'Pompki',
primaryMuscle: 'chest',
secondaryMuscles: ['triceps', 'core'],
equipment: ['bodyweight'],
hasReps: true, hasLoad: false, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Ćwiczenie wielostawowe z masą ciała.',
howTo: 'Pozycja deski, opuszczanie klatki do ziemi, prostowanie ramion.',
commonMistakes: 'Uginanie bioder, opadanie bioder, niedomknięcie w górze.',
difficulty: 2,
},
{
slug: 'cable-fly',
name: 'Rozpiętki na wyciągu',
primaryMuscle: 'chest',
secondaryMuscles: ['shoulders'],
equipment: ['cable'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Izolacja klatki — rozpiętki w wyciągu.',
howTo: 'Łokcie lekko ugięte, prowadzenie hantli w łuku do środka.',
commonMistakes: 'Zbyt duża amplituda (kontuzja barku), prostowanie łokci.',
difficulty: 2,
},
{
slug: 'dips',
name: 'Dipy',
primaryMuscle: 'chest',
secondaryMuscles: ['triceps', 'shoulders'],
equipment: ['dip-bars'],
hasReps: true, hasLoad: false, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wielostawowe ćwiczenie na klatkę i triceps.',
howTo: 'Chwyt na poręczach, pochyl tułów do przodu, opuszczaj biodra.',
commonMistakes: 'Zbyt głębokie opuszczenie, brak pochylenia tułowia.',
difficulty: 4,
},
{
slug: 'deadlift',
name: 'Martwy ciąg',
primaryMuscle: 'back',
secondaryMuscles: ['legs', 'core'],
equipment: ['barbell'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Najważniejsze ćwiczenie na całe ciało — plecy, nogi, core.',
howTo: 'Sztanga na środku stopy, prosta plecy, ciągnij biodra do przodu.',
commonMistakes: 'Okrągła plecy, odrywanie stóp, szarpanie sztangi.',
difficulty: 5,
},
{
slug: 'barbell-row',
name: 'Wiosłowanie sztangą',
primaryMuscle: 'back',
secondaryMuscles: ['biceps', 'core'],
equipment: ['barbell'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wiosłowanie w opadzie — gruba część pleców.',
howTo: 'Opad 45°, ciągnij sztangę do bioder, łokcie blisko tułowia.',
commonMistakes: 'Szarpanie tułowiem, zbyt pionowa sylwetka.',
difficulty: 4,
},
{
slug: 'lat-pulldown',
name: 'Podciąganie na wyciągu',
primaryMuscle: 'back',
secondaryMuscles: ['biceps'],
equipment: ['cable'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Alternatywa dla podciągnięć — najszerszy pleców.',
howTo: 'Chwyt szerszy niż barki, ciągnij do klatki, prowadź łokcie w dół.',
commonMistakes: 'Pochylanie tułowia do tyłu, szarpanie.',
difficulty: 2,
},
{
slug: 'pull-ups',
name: 'Podciąganie na drążku',
primaryMuscle: 'back',
secondaryMuscles: ['biceps', 'core'],
equipment: ['pull-up-bar'],
hasReps: true, hasLoad: false, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Klasyka na plecy — podciąganie masą ciała.',
howTo: 'Chwyt prosty szerszy niż barki, podciągaj brodę nad drążek.',
commonMistakes: 'Szarpanie, niedomknięcie, huśtanie.',
difficulty: 4,
},
{
slug: 'seated-cable-row',
name: 'Wiosłowanie siedząc na wyciągu',
primaryMuscle: 'back',
secondaryMuscles: ['biceps'],
equipment: ['cable'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wiosłowanie siedząc — kontrolowane obciążenie.',
howTo: 'Siedząc, ciągnij uchwyt do brzucha, łokcie w tył.',
commonMistakes: 'Rzucanie tułowiem, krótkie prowadzenie.',
difficulty: 2,
},
{
slug: 'squat',
name: 'Przysiad ze sztangą',
primaryMuscle: 'legs',
secondaryMuscles: ['core', 'glutes'],
equipment: ['barbell'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Król ćwiczeń na nogi.',
howTo: 'Sztanga na górnych plecach, siadaj w dół, kolana na zewnątrz.',
commonMistakes: 'Klęczenie kolan, opadanie bioder w dół, odbijanie w dole.',
difficulty: 5,
},
{
slug: 'leg-press',
name: 'Prasa nogi',
primaryMuscle: 'legs',
secondaryMuscles: ['glutes'],
equipment: ['leg-press'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Prasa — bezpieczna budowa nóg.',
howTo: 'Stopy na platformie, opuszczaj do 90° w kolanach.',
commonMistakes: 'Zbyt głębokie opuszczenie (odrywanie pośladków).',
difficulty: 3,
},
{
slug: 'lunges',
name: 'Wykroki z hantlami',
primaryMuscle: 'legs',
secondaryMuscles: ['glutes', 'core'],
equipment: ['dumbbells'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wykroki — praca jednostronna nóg.',
howTo: 'Krok w przód, kolano tylnej nogi blisko ziemi.',
commonMistakes: 'Krótki krok, kolano przednie poza stopę.',
difficulty: 3,
},
{
slug: 'leg-curl',
name: 'Uginanie nóg leżąc',
primaryMuscle: 'legs',
secondaryMuscles: [],
equipment: ['leg-curl'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Izolacja tylnej części uda.',
howTo: 'Leżąc na brzuchu, uginaj nogi do pośladków.',
commonMistakes: 'Szarpanie, odrywanie bioder.',
difficulty: 2,
},
{
slug: 'calf-raise',
name: 'Wspięcia na palce',
primaryMuscle: 'legs',
secondaryMuscles: [],
equipment: ['bodyweight'],
hasReps: true, hasLoad: false, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Izolacja łydek.',
howTo: 'Wspięcie na palce, pełne rozciągnięcie w dole.',
commonMistakes: 'Niedomknięcie w górze, brak pauzy.',
difficulty: 1,
},
{
slug: 'hip-thrust',
name: 'Hip thrust',
primaryMuscle: 'glutes',
secondaryMuscles: ['legs'],
equipment: ['barbell'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wyciskanie bioder — pośladki.',
howTo: 'Biodra na ławce, sztanga na biodrach, wyciskaj biodra w górę.',
commonMistakes: 'Wyciąganie lędźwi, niedomknięcie w górze.',
difficulty: 3,
},
{
slug: 'overhead-press',
name: 'OHP — wyciskanie nad głowę',
primaryMuscle: 'shoulders',
secondaryMuscles: ['triceps', 'core'],
equipment: ['barbell'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wyciskanie sztangi nad głowę — barki.',
howTo: 'Sztanga na obojczykach, wyciskanie nad głowę, napięte biodra.',
commonMistakes: 'Wyginanie lędźwi, brak napięcia core.',
difficulty: 4,
},
{
slug: 'lateral-raise',
name: 'Unoszenie hantli bokiem',
primaryMuscle: 'shoulders',
secondaryMuscles: [],
equipment: ['dumbbells'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Izolacja bocznej części barku.',
howTo: 'Unoszenie hantli bokiem do wysokości barków.',
commonMistakes: 'Szarpanie, zbyt duża waga.',
difficulty: 1,
},
{
slug: 'face-pull',
name: 'Face pull',
primaryMuscle: 'shoulders',
secondaryMuscles: ['back'],
equipment: ['cable'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wyciąganie do twarzy — tylny bark i rotatory.',
howTo: 'Uchwyt na wysokości twarzy, ciągnij do czoła, łokcie w tył.',
commonMistakes: 'Szarpanie, brak rotacji w górze.',
difficulty: 2,
},
{
slug: 'shrug',
name: 'Shrugi',
primaryMuscle: 'shoulders',
secondaryMuscles: [],
equipment: ['dumbbells'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wyciąganie barków — czepiec.',
howTo: 'Unoszenie barków do uszu, pauza w górze.',
commonMistakes: 'Szarpanie, brak pauzy.',
difficulty: 1,
},
{
slug: 'barbell-curl',
name: 'Uginanie na biceps ze sztangą',
primaryMuscle: 'biceps',
secondaryMuscles: [],
equipment: ['barbell'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Klasyka na biceps.',
howTo: 'Uginanie sztangi, łokcie przy tułowiu.',
commonMistakes: 'Szarpanie, odchylanie tułowia.',
difficulty: 2,
},
{
slug: 'hammer-curl',
name: 'Hammer curl',
primaryMuscle: 'biceps',
secondaryMuscles: ['forearms'],
equipment: ['dumbbells'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Uginanie młotkowe — biceps + przedramię.',
howTo: 'Hantle chwyciem neutralnym, uginanie.',
commonMistakes: 'Szarpanie, szarpanie łokciami.',
difficulty: 2,
},
{
slug: 'bicep-cable-curl',
name: 'Uginanie na wyciągu',
primaryMuscle: 'biceps',
secondaryMuscles: [],
equipment: ['cable'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Stałe napięcie bicepsa na wyciągu.',
howTo: 'Uginanie linki, łokcie przy tułowiu.',
commonMistakes: 'Szarpanie, odchylanie łokci.',
difficulty: 2,
},
{
slug: 'tricep-pushdown',
name: 'Prostowanie na wyciągu',
primaryMuscle: 'triceps',
secondaryMuscles: [],
equipment: ['cable'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Izolacja tricepsa.',
howTo: 'Prostowanie linki w dół, łokcie przy tułowiu.',
commonMistakes: 'Odchylanie łokci, szarpanie.',
difficulty: 2,
},
{
slug: 'overhead-tricep-extension',
name: 'Prostowanie hantla nad głową',
primaryMuscle: 'triceps',
secondaryMuscles: [],
equipment: ['dumbbells'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Dolna część tricepsa.',
howTo: 'Hantel za głową, prostowanie w górze.',
commonMistakes: 'Odchylanie tułowia, krótkie prowadzenie.',
difficulty: 2,
},
{
slug: 'close-grip-bench',
name: 'Wyciskanie hantli wąskim chwytem',
primaryMuscle: 'triceps',
secondaryMuscles: ['chest'],
equipment: ['barbell'],
hasReps: true, hasLoad: true, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Wyciskanie wąskim chwytem — triceps + klatka.',
howTo: 'Chwyt na szerokości barków, łokcie blisko tułowia.',
commonMistakes: 'Zbyt szeroki chwyt, odbijanie.',
difficulty: 3,
},
{
slug: 'plank',
name: 'Pływanie (plank)',
primaryMuscle: 'core',
secondaryMuscles: ['shoulders'],
equipment: ['bodyweight'],
hasReps: false, hasLoad: false, hasRest: true, hasSets: true, hasRir: false,
hasDifficulty: true, hasCardio: false, hasTime: true, hasSpeed: false,
description: 'Izolacja core — pozycja deski.',
howTo: 'Pozycja deski na przedramionach, prosta sylwetka.',
commonMistakes: 'Opadanie bioder, wdech w górze.',
difficulty: 1,
},
{
slug: 'crunches',
name: 'Brzuszki',
primaryMuscle: 'core',
secondaryMuscles: [],
equipment: ['bodyweight'],
hasReps: true, hasLoad: false, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Klasyczne brzuszki.',
howTo: 'Unoszenie łopatek od ziemi, napięcie core.',
commonMistakes: 'Szarpanie szyją, brak napięcia.',
difficulty: 1,
},
{
slug: 'russian-twist',
name: 'Rosyjskie skręty',
primaryMuscle: 'core',
secondaryMuscles: [],
equipment: ['bodyweight'],
hasReps: true, hasLoad: false, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Skręty tułowia — boki.',
howTo: 'Siedząc, skręty tułowia w lewo i prawo.',
commonMistakes: 'Szarpanie, odrywanie stóp.',
difficulty: 2,
},
{
slug: 'hanging-leg-raise',
name: 'Unoszenie nóg w zwisie',
primaryMuscle: 'core',
secondaryMuscles: ['legs'],
equipment: ['pull-up-bar'],
hasReps: true, hasLoad: false, hasRest: true, hasSets: true, hasRir: true,
hasDifficulty: true, hasCardio: false, hasTime: false, hasSpeed: false,
description: 'Dolne partie brzucha.',
howTo: 'Zwis na drążku, unoszenie nóg do poziomu bioder.',
commonMistakes: 'Szarpanie, huśtanie.',
difficulty: 4,
},
];

12
api/src/deps.ts Normal file
View File

@@ -0,0 +1,12 @@
import type { RequestHandler } from 'express';
import type { PrismaClient } from '@prisma/client';
/**
* Application dependencies, created once in the composition root (index.ts)
* and passed explicitly to app, routes, middleware and services.
*/
export interface AppDeps {
prisma: PrismaClient;
/** Nadpisanie globalnego rate limitera (testy). */
apiLimiter?: RequestHandler;
}

15
api/src/index.ts Normal file
View File

@@ -0,0 +1,15 @@
import { createApp } from './app.js';
import { config } from './config.js';
import { logger } from './lib/logger.js';
import { prisma } from './lib/prisma.js';
import { startScheduler } from './services/scheduler.js';
const app = createApp({ prisma });
const server = app.listen(config.port, () => {
logger.info({ port: config.port }, 'FitOS API started');
startScheduler(prisma);
});
export default app;
export { server };

View File

@@ -0,0 +1,96 @@
import { z } from 'zod';
export const EQUIPMENT_KINDS = [
'DUMBBELL',
'KETTLEBELL',
'BARBELL',
'CABLE',
'MACHINE',
'BENCH',
'CARDIO',
'BODYWEIGHT',
'OTHER',
] as const;
export type EquipmentKind = (typeof EQUIPMENT_KINDS)[number];
export interface LoadRangeSpec {
minKg: number;
maxKg: number;
}
export interface MaxLoadSpec {
maxLoadKg: number;
}
export interface CardioSpec {
maxSpeedKmh?: number;
maxInclinePct?: number;
}
export type EquipmentSpec = LoadRangeSpec | MaxLoadSpec | CardioSpec | null;
const loadRangeSpec = z
.object({
minKg: z.number().positive().max(500),
maxKg: z.number().positive().max(500),
})
.refine((v) => v.minKg <= v.maxKg, { message: 'minKg must be <= maxKg' });
const maxLoadSpec = z.object({ maxLoadKg: z.number().positive().max(1000) });
const cardioSpec = z.object({
maxSpeedKmh: z.number().positive().max(50).optional(),
maxInclinePct: z.number().min(0).max(40).optional(),
});
const noSpec = z.object({});
/** Spec schema per equipment kind. */
const SPEC_BY_KIND: Record<EquipmentKind, z.ZodTypeAny> = {
DUMBBELL: loadRangeSpec,
KETTLEBELL: loadRangeSpec,
CABLE: loadRangeSpec,
MACHINE: loadRangeSpec,
BARBELL: maxLoadSpec,
BENCH: maxLoadSpec,
CARDIO: cardioSpec,
BODYWEIGHT: noSpec,
OTHER: noSpec,
};
/** Kinds whose spec payload is mandatory. */
const REQUIRED_SPEC: ReadonlySet<EquipmentKind> = new Set([
'DUMBBELL',
'KETTLEBELL',
'BARBELL',
'CABLE',
'MACHINE',
'BENCH',
]);
export const equipmentKindSchema = z.enum(EQUIPMENT_KINDS);
/**
* Validate a `spec` payload against an equipment `kind`.
* Mandatory for load-bearing kinds, optional for CARDIO, forbidden-ish (ignored) for BODYWEIGHT/OTHER.
*/
export function validateEquipmentSpec(
kind: EquipmentKind,
spec: unknown,
): { ok: true; spec: EquipmentSpec } | { ok: false; error: string } {
if (spec == null) {
if (REQUIRED_SPEC.has(kind)) return { ok: false, error: `spec is required for kind ${kind}` };
return { ok: true, spec: null };
}
if (kind === 'BODYWEIGHT' || kind === 'OTHER') {
return { ok: false, error: `spec is not allowed for kind ${kind}` };
}
const parsed = SPEC_BY_KIND[kind].safeParse(spec);
if (!parsed.success) {
const issue = parsed.error.issues[0];
const path = issue?.path.length ? `${issue.path.join('.')} ` : '';
return { ok: false, error: `invalid spec for kind ${kind}: ${path}${issue?.message ?? 'unknown'}` };
}
return { ok: true, spec: parsed.data as EquipmentSpec };
}

19
api/src/lib/errors.ts Normal file
View File

@@ -0,0 +1,19 @@
export class AppError extends Error {
constructor(
public status: number,
public code: string,
message: string,
public details?: unknown,
) {
super(message);
}
}
export const badRequest = (message: string, details?: unknown) =>
new AppError(400, 'BAD_REQUEST', message, details);
export const unauthorized = (message = 'Unauthorized') =>
new AppError(401, 'UNAUTHORIZED', message);
export const forbidden = (message = 'Forbidden') =>
new AppError(403, 'FORBIDDEN', message);
export const notFound = (message = 'Not found') => new AppError(404, 'NOT_FOUND', message);
export const conflict = (message: string) => new AppError(409, 'CONFLICT', message);

34
api/src/lib/jwt.ts Normal file
View File

@@ -0,0 +1,34 @@
import jwt from 'jsonwebtoken';
import { config } from '../config.js';
export interface TokenPayload {
sub: string;
tv: number;
type: 'access' | 'refresh';
}
export const REFRESH_COOKIE = 'fitos_refresh';
export function signAccessToken(userId: string, tokenVersion: number): string {
return jwt.sign({ sub: userId, tv: tokenVersion, type: 'access' }, config.jwt.accessSecret, {
expiresIn: config.jwt.accessTtlSec,
});
}
export function signRefreshToken(userId: string, tokenVersion: number): string {
return jwt.sign({ sub: userId, tv: tokenVersion, type: 'refresh' }, config.jwt.refreshSecret, {
expiresIn: config.jwt.refreshTtlSec,
});
}
export function verifyAccessToken(token: string): TokenPayload {
const payload = jwt.verify(token, config.jwt.accessSecret) as TokenPayload;
if (payload.type !== 'access') throw new Error('invalid token type');
return payload;
}
export function verifyRefreshToken(token: string): TokenPayload {
const payload = jwt.verify(token, config.jwt.refreshSecret) as TokenPayload;
if (payload.type !== 'refresh') throw new Error('invalid token type');
return payload;
}

7
api/src/lib/logger.ts Normal file
View File

@@ -0,0 +1,7 @@
import pino from 'pino';
import { config } from '../config.js';
export const logger = pino({
level: config.logLevel,
...(config.nodeEnv === 'development' ? {} : { transport: undefined }),
});

13
api/src/lib/prisma.ts Normal file
View File

@@ -0,0 +1,13 @@
import { PrismaClient } from '@prisma/client';
export const prisma = new PrismaClient();
/** Prisma "record not found" error (P2025) — update/delete on a missing row. */
export function isPrismaNotFound(e: unknown): boolean {
return (e as { code?: string } | null)?.code === 'P2025';
}
/** Prisma unique constraint violation (P2002). */
export function isPrismaUnique(e: unknown): boolean {
return (e as { code?: string } | null)?.code === 'P2002';
}

24
api/src/lib/publicUser.ts Normal file
View File

@@ -0,0 +1,24 @@
import type { User } from '@prisma/client';
export function publicUser(u: User) {
return {
id: u.id,
email: u.email,
firstName: u.firstName,
lastName: u.lastName,
nickname: u.nickname,
socialMedia: u.socialMedia,
age: u.age,
heightCm: u.heightCm,
phone: u.phone,
isAdmin: u.isAdmin,
availability: u.availability,
priorities: u.priorities,
exclusions: u.exclusions,
developMuscles: u.developMuscles,
canDoMuscles: u.canDoMuscles,
difficultMuscles: u.difficultMuscles,
avoidMuscles: u.avoidMuscles,
createdAt: u.createdAt,
};
}

132
api/src/lib/uploads.ts Normal file
View File

@@ -0,0 +1,132 @@
import fs from 'node:fs';
import path from 'node:path';
import { randomBytes } from 'node:crypto';
import multer from 'multer';
import { config } from '../config.js';
import { logger } from './logger.js';
export const CLAIM_FILE_MIME_TYPES = ['image/jpeg', 'image/png', 'application/pdf'] as const;
export const MAX_CLAIM_FILES = 5;
export const MAX_CLAIM_FILE_SIZE = 5 * 1024 * 1024;
/** Multer multipart limit: 5 files x 5 MB + field overhead. */
export const CLAIM_MULTIPART_LIMIT = 25 * 1024 * 1024;
export const PHOTO_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp'] as const;
export const MAX_PHOTO_FILES = 10;
export const MAX_PHOTO_FILE_SIZE = 5 * 1024 * 1024;
/** Max photos per gym (total, across uploads). */
export const MAX_GYM_PHOTOS = 20;
const EXT_BY_MIME: Record<string, string> = {
'image/jpeg': '.jpg',
'image/png': '.png',
'image/webp': '.webp',
'application/pdf': '.pdf',
};
export function storedFileName(mimeType: string): string {
return `${randomBytes(12).toString('hex')}${EXT_BY_MIME[mimeType] ?? ''}`;
}
export function claimUploadDir(claimId: string): string {
return path.join(config.uploadDir, claimId);
}
const tmpDir = path.join(config.uploadDir, 'tmp');
/**
* Multer for gym claim documents: files land in a temp dir first (the claim row —
* and thus the per-claim directory — does not exist yet); the service moves them.
*/
export const claimUpload = multer({
storage: multer.diskStorage({
destination: (_req, _file, cb) => {
try {
fs.mkdirSync(tmpDir, { recursive: true });
cb(null, tmpDir);
} catch (e) {
cb(e as Error, tmpDir);
}
},
filename: (_req, file, cb) => {
cb(null, storedFileName(file.mimetype));
},
}),
limits: { fileSize: MAX_CLAIM_FILE_SIZE, files: MAX_CLAIM_FILES },
fileFilter: (_req, file, cb) => {
if ((CLAIM_FILE_MIME_TYPES as readonly string[]).includes(file.mimetype)) cb(null, true);
else cb(new Error(`Unsupported file type: ${file.mimetype}`));
},
});
export function photoUploadDir(gymId: string): string {
return path.join(config.uploadDir, 'gyms', gymId);
}
/**
* Multer for gym gallery photos: files land in a temp dir first; the service
* moves them into UPLOAD_DIR/gyms/<gymId>/.
*/
export const gymPhotoUpload = multer({
storage: multer.diskStorage({
destination: (_req, _file, cb) => {
try {
fs.mkdirSync(tmpDir, { recursive: true });
cb(null, tmpDir);
} catch (e) {
cb(e as Error, tmpDir);
}
},
filename: (_req, file, cb) => {
cb(null, storedFileName(file.mimetype));
},
}),
limits: { fileSize: MAX_PHOTO_FILE_SIZE, files: MAX_PHOTO_FILES },
fileFilter: (_req, file, cb) => {
if ((PHOTO_MIME_TYPES as readonly string[]).includes(file.mimetype)) cb(null, true);
else cb(new Error(`Unsupported file type: ${file.mimetype}`));
},
});
/** Remove one gym photo file (best-effort — errors are logged only). */
export function removeGymPhotoFile(gymId: string, storedName: string): void {
try {
fs.rmSync(path.join(photoUploadDir(gymId), storedName), { force: true });
} catch (e) {
logger.warn({ err: e, gymId, storedName }, 'Failed to remove gym photo file');
}
}
/** Remove all of a gym's photo files (best-effort — errors are logged only). */
export function removeGymPhotoFiles(gymId: string): void {
try {
fs.rmSync(photoUploadDir(gymId), { recursive: true, force: true });
} catch (e) {
logger.warn({ err: e, gymId }, 'Failed to remove gym photo files');
}
}
/** Remove a claim's uploaded files (best-effort — errors are logged only). */
export function removeClaimFiles(claimId: string): void {
try {
fs.rmSync(claimUploadDir(claimId), { recursive: true, force: true });
} catch (e) {
logger.warn({ err: e, claimId }, 'Failed to remove claim files');
}
}
/** Remove uploaded files of all claims linked to a gym (best-effort). */
export async function removeGymClaimFiles(claimIds: string[]): Promise<void> {
for (const claimId of claimIds) removeClaimFiles(claimId);
}
/** Remove leftover temp files (after a failed claim creation). */
export function removeTmpFiles(files: { path: string }[]): void {
for (const f of files) {
try {
fs.rmSync(f.path, { force: true });
} catch (e) {
logger.warn({ err: e, path: f.path }, 'Failed to remove temp upload file');
}
}
}

View File

@@ -0,0 +1,48 @@
import type { NextFunction, Request, Response } from 'express';
import type { PrismaClient } from '@prisma/client';
import { verifyAccessToken } from '../lib/jwt.js';
import { AppError, forbidden, unauthorized } from '../lib/errors.js';
declare global {
namespace Express {
interface Request {
user?: { id: string; isAdmin: boolean; tokenVersion: number };
}
}
}
export function authenticate(prisma: PrismaClient) {
return async (req: Request, _res: Response, next: NextFunction) => {
try {
const header = req.headers.authorization;
if (!header || !header.startsWith('Bearer ')) throw unauthorized('Missing access token');
const payload = verifyAccessToken(header.slice(7));
const user = await prisma.user.findUnique({ where: { id: payload.sub } });
if (!user || user.tokenVersion !== payload.tv) throw unauthorized('Token revoked');
req.user = { id: user.id, isAdmin: user.isAdmin, tokenVersion: user.tokenVersion };
next();
} catch (e) {
next(e instanceof AppError ? e : unauthorized('Invalid or expired token'));
}
};
}
export function requireAdmin(req: Request, _res: Response, next: NextFunction) {
if (!req.user?.isAdmin) return next(forbidden('Admin access required'));
next();
}
/** The user must hold the TRAINER role in at least one gym. */
export function requireTrainer(prisma: PrismaClient) {
return async (req: Request, _res: Response, next: NextFunction) => {
try {
const membership = await prisma.gymMembership.findFirst({
where: { userId: req.user!.id, roles: { has: 'TRAINER' } },
});
if (!membership) return next(forbidden('Trainer role required'));
next();
} catch (e) {
next(e);
}
};
}

View File

@@ -0,0 +1,23 @@
import { NextFunction, Request, Response } from 'express';
import { ZodError } from 'zod';
import { AppError } from '../lib/errors.js';
import { logger } from '../lib/logger.js';
export function errorHandler(err: unknown, req: Request, res: Response, _next: NextFunction) {
if (err instanceof AppError) {
return res.status(err.status).json({
error: { code: err.code, message: err.message, details: err.details },
});
}
if (err instanceof ZodError) {
return res.status(400).json({
error: { code: 'VALIDATION_ERROR', message: 'Validation failed', details: err.flatten() },
});
}
logger.error({ err, path: req.path }, 'Unhandled error');
res.status(500).json({ error: { code: 'INTERNAL_ERROR', message: 'Internal server error' } });
}
export function notFoundHandler(_req: Request, res: Response) {
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Route not found' } });
}

View File

@@ -0,0 +1,20 @@
import rateLimit from 'express-rate-limit';
/** Standard error body — spójny z resztą API (JSON, nie plain text). */
export const RATE_LIMIT_BODY = { error: { code: 'RATE_LIMITED', message: 'Too many requests, try later' } };
export const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 300,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: RATE_LIMIT_BODY,
});
export const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 20,
standardHeaders: 'draft-7',
legacyHeaders: false,
message: { error: { code: 'RATE_LIMITED', message: 'Too many attempts, try later' } },
});

View File

@@ -0,0 +1,14 @@
import { NextFunction, Request, Response } from 'express';
import { ZodType } from 'zod';
import { badRequest } from '../lib/errors.js';
export function validate(schema: ZodType, source: 'body' | 'query' | 'params' = 'body') {
return (req: Request, _res: Response, next: NextFunction) => {
const result = schema.safeParse(req[source]);
if (!result.success) {
return next(badRequest('Validation failed', result.error.flatten()));
}
(req as unknown as Record<string, unknown>)[source] = result.data;
next();
};
}

790
api/src/routes/admin.ts Normal file
View File

@@ -0,0 +1,790 @@
import fs from 'node:fs';
import path from 'node:path';
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate, requireAdmin } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import { availabilitySchema } from './me.js';
import {
addGymEquipment,
addMembership,
approveGymClaim,
createGym,
createUser,
deleteGym,
deleteUser,
getGym,
getGymClaim,
listGymClaims,
listGyms,
listUsers,
rejectGymClaim,
removeGymEquipment,
removeMembership,
updateGym,
updateGymEquipmentQuantity,
updateMembership,
updateUser,
} from '../services/admin.js';
import { config } from '../config.js';
import { notFound } from '../lib/errors.js';
import {
createFocusArea,
deleteFocusArea,
listFocusAreas,
updateFocusArea,
} from '../services/focusAreas.js';
import { getFocusChain } from '../services/focusChain.js';
import {
createGymException,
deleteGymException,
listGymExceptions,
} from '../services/gyms.js';
import { listActivityLogs, logActivity } from '../services/audit.js';
const gymSchema = z.object({
name: z.string().min(1).max(200),
location: z.string().max(500).nullable().optional(),
availability: availabilitySchema,
capacity: z.number().int().positive().max(100000).nullable().optional(),
});
const createGymSchema = gymSchema;
const updateGymSchema = gymSchema.partial();
const gymExceptionSchema = z.object({
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
availability: z
.object({
start: z.string().regex(/^\d{2}:\d{2}$/),
end: z.string().regex(/^\d{2}:\d{2}$/),
})
.nullable()
.optional(),
});
const createUserSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
firstName: z.string().min(1).max(100).optional(),
lastName: z.string().min(1).max(100).optional(),
age: z.number().int().min(10).max(100).optional(),
isAdmin: z.boolean().optional(),
});
const muscleArraySchema = z.array(z.string().min(1).max(50)).max(20);
const updateUserSchema = z.object({
email: z.string().email().max(200).optional(),
firstName: z.string().min(1).max(100).nullable().optional(),
lastName: z.string().min(1).max(100).nullable().optional(),
age: z.number().int().min(10).max(100).nullable().optional(),
heightCm: z.number().positive().max(250).nullable().optional(),
phone: z.string().min(5).max(20).nullable().optional(),
isAdmin: z.boolean().optional(),
password: z.string().min(8).optional(),
availability: availabilitySchema,
priorities: z.string().max(2000).nullable().optional(),
exclusions: z.string().max(2000).nullable().optional(),
developMuscles: muscleArraySchema.optional(),
canDoMuscles: muscleArraySchema.optional(),
difficultMuscles: muscleArraySchema.optional(),
avoidMuscles: muscleArraySchema.optional(),
});
const GYM_ROLES = ['OWNER', 'TRAINER', 'MEMBER'] as const;
const membershipSchema = z.object({
gymId: z.string().min(1),
roles: z.array(z.enum(GYM_ROLES)).min(1),
});
const updateMembershipSchema = z.object({
roles: z.array(z.enum(GYM_ROLES)).min(1),
});
export function createAdminRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma), requireAdmin);
/**
* @openapi
* /admin/gyms:
* get:
* summary: List gyms (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get('/gyms', async (_req, res, next) => {
try {
const result = await listGyms(prisma);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/gyms:
* post:
* summary: Create gym (admin)
* tags: [Admin]
* responses:
* 201: { description: Created }
*/
router.post('/gyms', validate(createGymSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof createGymSchema>;
const result = await createGym(prisma, data);
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/gyms/{id}:
* patch:
* summary: Update gym (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.patch('/gyms/:id', validate(updateGymSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof updateGymSchema>;
const result = await updateGym(prisma, req.params.id, data);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/gyms/{id}:
* delete:
* summary: Delete gym (admin). Memberships are removed; user plans are kept.
* tags: [Admin]
* responses:
* 204: { description: Deleted }
*/
router.delete('/gyms/:id', async (req, res, next) => {
try {
await deleteGym(prisma, req.params.id);
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/gyms/{id}/exceptions:
* get:
* summary: List a gym's schedule exceptions (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get('/gyms/:id/exceptions', async (req, res, next) => {
try {
const result = await listGymExceptions(prisma, req.params.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/gyms/{id}/exceptions:
* post:
* summary: Add a one-off schedule exception (admin)
* tags: [Admin]
* responses:
* 201: { description: Created }
* 409: { description: Exception already exists for this date }
*/
router.post(
'/gyms/:id/exceptions',
validate(gymExceptionSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof gymExceptionSchema>;
const result = await createGymException(prisma, req.params.id, {
date: data.date,
availability: data.availability ?? null,
});
res.status(201).json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /admin/gyms/{id}/exceptions/{exceptionId}:
* delete:
* summary: Remove a schedule exception (admin)
* tags: [Admin]
* responses:
* 204: { description: Removed }
*/
router.delete('/gyms/:id/exceptions/:exceptionId', async (req, res, next) => {
try {
await deleteGymException(prisma, req.params.id, req.params.exceptionId);
res.status(204).end();
} catch (e) {
next(e);
}
});
const gymEquipmentSchema = z.object({
equipmentId: z.string().min(1),
quantity: z.number().int().min(1).max(10000).optional(),
});
const gymEquipmentQuantitySchema = z.object({
quantity: z.number().int().min(1).max(10000),
});
/**
* @openapi
* /admin/gyms/{id}/equipment:
* post:
* summary: Add a catalog equipment item to a gym with a quantity (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
* 404: { description: Gym or equipment not found }
* 409: { description: Equipment already exists (update its quantity instead) }
*/
router.post(
'/gyms/:id/equipment',
validate(gymEquipmentSchema),
async (req, res, next) => {
try {
const { equipmentId, quantity } = req.body as z.infer<typeof gymEquipmentSchema>;
const result = await addGymEquipment(
prisma,
req.params.id,
equipmentId,
quantity ?? 1,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /admin/gyms/{id}/equipment/{equipmentId}:
* patch:
* summary: Change the quantity of a gym's equipment item (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
* 400: { description: Equipment not in gym }
* 404: { description: Gym not found }
*/
router.patch(
'/gyms/:id/equipment/:equipmentId',
validate(gymEquipmentQuantitySchema),
async (req, res, next) => {
try {
const { quantity } = req.body as z.infer<typeof gymEquipmentQuantitySchema>;
const result = await updateGymEquipmentQuantity(
prisma,
req.params.id,
req.params.equipmentId,
quantity,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /admin/gyms/{id}/equipment/{equipmentId}:
* delete:
* summary: Remove a catalog equipment item from a gym (admin)
* tags: [Admin]
* responses:
* 204: { description: Removed }
* 400: { description: Equipment not in gym }
* 404: { description: Gym not found }
*/
router.delete('/gyms/:id/equipment/:equipmentId', async (req, res, next) => {
try {
await removeGymEquipment(prisma, req.params.id, req.params.equipmentId);
res.status(204).end();
} catch (e) {
next(e);
}
});
const claimsQuerySchema = z.object({
status: z.enum(['PENDING', 'APPROVED', 'REJECTED']).optional(),
});
/**
* @openapi
* /admin/gyms/claims:
* get:
* summary: List gym claims (admin, optional ?status=)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get('/gyms/claims', validate(claimsQuerySchema, 'query'), async (req, res, next) => {
try {
const q = req.query as z.infer<typeof claimsQuerySchema>;
const result = await listGymClaims(prisma, q.status);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/gyms/claims/{id}:
* get:
* summary: Gym claim detail (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
* 404: { description: Claim not found }
*/
router.get('/gyms/claims/:id', async (req, res, next) => {
try {
const result = await getGymClaim(prisma, req.params.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/gyms/claims/{id}/documents/{docId}:
* get:
* summary: Download a claim document (admin)
* tags: [Admin]
* responses:
* 200: { description: File (attachment) }
* 404: { description: Claim or document not found }
*/
router.get('/gyms/claims/:id/documents/:docId', async (req, res, next) => {
try {
const claim = await prisma.gymClaim.findUnique({
where: { id: req.params.id },
include: {
documents: { select: { id: true, originalName: true, storedName: true } },
},
});
if (!claim) throw notFound('Claim not found');
const doc = claim.documents.find((d) => d.id === req.params.docId);
if (!doc) throw notFound('Document not found');
const filePath = path.join(config.uploadDir, claim.id, doc.storedName);
if (!fs.existsSync(filePath)) throw notFound('Document file missing');
const safeName = doc.originalName.replace(/[\\/]/g, '_');
res.download(filePath, safeName);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/gyms/claims/{id}/approve:
* post:
* summary: Approve a gym claim (admin) — virtual → REAL or creates a new REAL gym
* tags: [Admin]
* responses:
* 200: { description: Approved }
* 404: { description: Claim not found }
* 409: { description: Claim is not pending }
*/
router.post('/gyms/claims/:id/approve', async (req, res, next) => {
try {
await approveGymClaim(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.claim.approved',
entityType: 'gym-claim',
entityId: req.params.id,
});
res.json({ ok: true });
} catch (e) {
next(e);
}
});
const rejectClaimSchema = z.object({
reason: z.string().max(1000).optional(),
});
/**
* @openapi
* /admin/gyms/claims/{id}/reject:
* post:
* summary: Reject a gym claim with an optional reason (admin)
* tags: [Admin]
* responses:
* 200: { description: Rejected }
* 404: { description: Claim not found }
* 409: { description: Claim is not pending }
*/
router.post(
'/gyms/claims/:id/reject',
validate(rejectClaimSchema),
async (req, res, next) => {
try {
const { reason } = req.body as z.infer<typeof rejectClaimSchema>;
await rejectGymClaim(prisma, req.user!.id, req.params.id, reason);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.claim.rejected',
entityType: 'gym-claim',
entityId: req.params.id,
details: { reason: reason ?? null },
});
res.json({ ok: true });
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /admin/gyms/{id}:
* get:
* summary: Get gym detail (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
* 404: { description: Gym not found }
*/
router.get('/gyms/:id', async (req, res, next) => {
try {
const gym = await getGym(prisma, req.params.id);
res.json(gym);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/users:
* get:
* summary: List users (admin, optional ?search=)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get('/users', async (req, res, next) => {
try {
const search = req.query.search as string | undefined;
const result = await listUsers(prisma, search);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/users:
* post:
* summary: Create user (admin)
* tags: [Admin]
* responses:
* 201: { description: Created }
* 409: { description: Email already registered }
*/
router.post('/users', validate(createUserSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof createUserSchema>;
const result = await createUser(prisma, data);
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/users/{id}:
* patch:
* summary: Update user (admin). Role change increments token_version (JWT revocation).
* tags: [Admin]
* responses:
* 200: { description: OK }
* 404: { description: User not found }
* 409: { description: Email already registered }
*/
router.patch('/users/:id', validate(updateUserSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof updateUserSchema>;
const result = await updateUser(prisma, req.params.id, data);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/users/{id}:
* delete:
* summary: Delete user (admin). Plans/sessions are cascade-deleted.
* tags: [Admin]
* responses:
* 204: { description: Deleted }
*/
router.delete('/users/:id', async (req, res, next) => {
try {
await deleteUser(prisma, req.params.id);
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/users/{id}/memberships:
* post:
* summary: Assign gym membership/role (admin)
* tags: [Admin]
* responses:
* 201: { description: Created }
* 409: { description: Membership already exists }
*/
router.post(
'/users/:id/memberships',
validate(membershipSchema),
async (req, res, next) => {
try {
const { gymId, roles } = req.body as z.infer<typeof membershipSchema>;
const result = await addMembership(prisma, req.params.id, gymId, roles);
res.status(201).json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /admin/users/{id}/memberships/{gymId}:
* patch:
* summary: Change gym membership role (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
* 404: { description: Membership not found }
*/
router.patch(
'/users/:id/memberships/:gymId',
validate(updateMembershipSchema),
async (req, res, next) => {
try {
const { roles } = req.body as z.infer<typeof updateMembershipSchema>;
const result = await updateMembership(prisma, req.params.id, req.params.gymId, roles);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /admin/users/{id}/memberships/{gymId}:
* delete:
* summary: Remove gym membership (admin)
* tags: [Admin]
* responses:
* 204: { description: Deleted }
*/
router.delete('/users/:id/memberships/:gymId', async (req, res, next) => {
try {
await removeMembership(prisma, req.params.id, req.params.gymId);
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/users/{id}/focus-chain:
* get:
* summary: User's causal chain — priority/exclusion muscles linked to active plan exercises (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
* 404: { description: User not found }
*/
router.get('/users/:id/focus-chain', async (req, res, next) => {
try {
const result = await getFocusChain(prisma, req.params.id);
res.json(result);
} catch (e) {
next(e);
}
});
const logsQuerySchema = z.object({
action: z.string().min(1).max(100).optional(),
userId: z.string().min(1).max(100).optional(),
from: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
to: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
limit: z.coerce.number().int().min(1).max(500).optional(),
offset: z.coerce.number().int().min(0).optional(),
});
/**
* @openapi
* /admin/logs:
* get:
* summary: Activity log — user actions from the app (admin).
* Query: action, userId, from/to (YYYY-MM-DD), limit (default 100, max 500), offset (default 0).
* tags: [Admin]
* responses:
* 200: { description: OK, returns { logs, total } }
*/
router.get('/logs', validate(logsQuerySchema, 'query'), async (req, res, next) => {
try {
const q = req.query as z.infer<typeof logsQuerySchema>;
const result = await listActivityLogs(prisma, {
action: q.action,
userId: q.userId,
from: q.from,
to: q.to,
limit: q.limit ?? 100,
offset: q.offset ?? 0,
});
res.json(result);
} catch (e) {
next(e);
}
});
const focusAreaSchema = z.object({
name: z.string().min(1).max(100),
muscle: z.string().min(1).max(50),
description: z.string().max(500).nullable().optional(),
setsMin: z.number().int().min(0).max(100).nullable().optional(),
setsMax: z.number().int().min(0).max(100).nullable().optional(),
});
const focusAreaUpdateSchema = z.object({
name: z.string().min(1).max(100).optional(),
muscle: z.string().min(1).max(50).optional(),
description: z.string().max(500).nullable().optional(),
setsMin: z.number().int().min(0).max(100).nullable().optional(),
setsMax: z.number().int().min(0).max(100).nullable().optional(),
});
/**
* @openapi
* /admin/focus-areas:
* get:
* summary: List focus areas (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
*/
router.get('/focus-areas', async (_req, res, next) => {
try {
const result = await listFocusAreas(prisma);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/focus-areas:
* post:
* summary: Create a focus area (admin)
* tags: [Admin]
* responses:
* 201: { description: Created }
* 409: { description: Muscle already exists }
*/
router.post(
'/focus-areas',
validate(focusAreaSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof focusAreaSchema>;
const result = await createFocusArea(prisma, data);
res.status(201).json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /admin/focus-areas/{id}:
* patch:
* summary: Update a focus area (admin)
* tags: [Admin]
* responses:
* 200: { description: OK }
* 404: { description: Not found }
*/
router.patch(
'/focus-areas/:id',
validate(focusAreaUpdateSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof focusAreaUpdateSchema>;
const result = await updateFocusArea(prisma, req.params.id, data);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /admin/focus-areas/{id}:
* delete:
* summary: Delete a focus area (admin)
* tags: [Admin]
* responses:
* 204: { description: Deleted }
* 404: { description: Not found }
*/
router.delete('/focus-areas/:id', async (req, res, next) => {
try {
await deleteFocusArea(prisma, req.params.id);
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

136
api/src/routes/auth.ts Normal file
View File

@@ -0,0 +1,136 @@
import { Router } from 'express';
import type { Response } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { config } from '../config.js';
import { REFRESH_COOKIE } from '../lib/jwt.js';
import { validate } from '../middleware/validate.js';
import { authLimiter } from '../middleware/rateLimit.js';
import { AppError, unauthorized } from '../lib/errors.js';
import { login, register, refresh } from '../services/auth.js';
import { logActivity } from '../services/audit.js';
const registerSchema = z.object({
email: z.string().email(),
password: z.string().min(8),
firstName: z.string().min(1).max(100).optional(),
lastName: z.string().min(1).max(100).optional(),
});
const loginSchema = z.object({
email: z.string().email(),
password: z.string(),
});
function setRefreshCookie(res: Response, token: string) {
res.cookie(REFRESH_COOKIE, token, {
httpOnly: true,
sameSite: 'lax',
secure: config.cookieSecure,
maxAge: 7 * 24 * 3600 * 1000,
path: '/',
});
}
export function createAuthRoutes({ prisma }: AppDeps) {
const router = Router();
/**
* @openapi
* /auth/register:
* post:
* summary: Self-registration (default role: member, no gym membership)
* tags: [Auth]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* required: [email, password]
* properties:
* email: { type: string }
* password: { type: string }
* firstName: { type: string }
* lastName: { type: string }
* responses:
* 201: { description: Created, returns user + access token }
* 409: { description: Email already registered }
*/
router.post('/register', authLimiter, validate(registerSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof registerSchema>;
const result = await register(prisma, data);
await logActivity(prisma, {
actorId: result.user.id,
action: 'user.registered',
entityType: 'user',
entityId: result.user.id,
details: { email: result.user.email },
});
setRefreshCookie(res, result.refreshToken);
res.status(201).json({ user: result.user, accessToken: result.accessToken });
} catch (e) {
next(e);
}
});
/**
* @openapi
* /auth/login:
* post:
* summary: Login with email + password
* tags: [Auth]
* responses:
* 200: { description: OK, returns user + access token }
* 401: { description: Invalid credentials }
*/
router.post('/login', authLimiter, validate(loginSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof loginSchema>;
const result = await login(prisma, data);
setRefreshCookie(res, result.refreshToken);
res.json({ user: result.user, accessToken: result.accessToken });
} catch (e) {
next(e);
}
});
/**
* @openapi
* /auth/refresh:
* post:
* summary: Refresh access token (refresh token from httpOnly cookie)
* tags: [Auth]
* responses:
* 200: { description: OK, returns new access token }
* 401: { description: Missing/invalid/revoked refresh token }
*/
router.post('/refresh', async (req, res, next) => {
try {
const token = (req.cookies as Record<string, string | undefined>)[REFRESH_COOKIE];
if (!token) throw unauthorized('Missing refresh token');
const result = await refresh(prisma, token);
res.json(result);
} catch (e) {
res.clearCookie(REFRESH_COOKIE, { path: '/' });
next(e instanceof AppError ? e : unauthorized('Invalid refresh token'));
}
});
/**
* @openapi
* /auth/logout:
* post:
* summary: Logout (clears refresh cookie)
* tags: [Auth]
* responses:
* 204: { description: No content }
*/
router.post('/logout', (_req, res) => {
res.clearCookie(REFRESH_COOKIE, { path: '/' });
res.status(204).end();
});
return router;
}

View File

@@ -0,0 +1,39 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import { getCalendar } from '../services/calendar.js';
const querySchema = z.object({
month: z
.string()
.regex(/^\d{4}-(0[1-9]|1[0-2])$/, 'Expected YYYY-MM')
.optional(),
});
export function createCalendarRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /calendar:
* get:
* summary: Calendar — training days of the active plan in a month (YYYY-MM, default: current)
* tags: [Calendar]
* responses:
* 200: { description: OK }
*/
router.get('/', validate(querySchema, 'query'), async (req, res, next) => {
try {
const { month } = req.query as z.infer<typeof querySchema>;
const result = await getCalendar(prisma, req.user!.id, month);
res.json(result);
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,29 @@
import { Router } from 'express';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { getDashboard } from '../services/dashboard.js';
export function createDashboardRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /dashboard:
* get:
* summary: Dashboard — killstreak, next training, plan progress, extra (non-planned) work
* tags: [Dashboard]
* responses:
* 200: { description: OK }
*/
router.get('/', async (req, res, next) => {
try {
const result = await getDashboard(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
return router;
}

123
api/src/routes/equipment.ts Normal file
View File

@@ -0,0 +1,123 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate, requireAdmin } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import {
createEquipment,
deleteEquipment,
listEquipment,
updateEquipment,
} from '../services/equipment.js';
import { equipmentKindSchema, validateEquipmentSpec } from '../lib/equipmentSpec.js';
/**
* Equipment catalog entry. `kind` determines the shape of the type-specific `spec` payload:
* DUMBBELL/KETTLEBELL/CABLE/MACHINE → { minKg, maxKg }
* BARBELL/BENCH → { maxLoadKg }
* CARDIO → { maxSpeedKmh?, maxInclinePct? } (optional)
* BODYWEIGHT/OTHER → no spec
*/
const equipmentSchema = z
.object({
name: z.string().min(1).max(100),
description: z.string().max(500).nullable().optional(),
kind: equipmentKindSchema,
spec: z.unknown().optional(),
})
.superRefine((val, ctx) => {
const checked = validateEquipmentSpec(val.kind, val.spec);
if (!checked.ok) ctx.addIssue({ code: z.ZodIssueCode.custom, message: checked.error, path: ['spec'] });
});
/** Partial update — `spec` is validated against the resulting `kind` in the service. */
const equipmentUpdateSchema = z.object({
name: z.string().min(1).max(100).optional(),
description: z.string().max(500).nullable().optional(),
kind: equipmentKindSchema.optional(),
spec: z.unknown().optional(),
});
export function createEquipmentRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma), requireAdmin);
/**
* @openapi
* /admin/equipment:
* get:
* summary: List the equipment (machine/device) catalog (admin)
* tags: [Equipment]
* responses:
* 200: { description: OK }
*/
router.get('/', async (_req, res, next) => {
try {
const result = await listEquipment(prisma);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/equipment:
* post:
* summary: Create an equipment catalog entry (admin)
* tags: [Equipment]
* responses:
* 201: { description: Created }
* 409: { description: Name already exists }
*/
router.post('/', validate(equipmentSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof equipmentSchema>;
const result = await createEquipment(prisma, data);
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/equipment/{id}:
* patch:
* summary: Update an equipment catalog entry (admin)
* tags: [Equipment]
* responses:
* 200: { description: OK }
* 404: { description: Not found }
*/
router.patch('/:id', validate(equipmentUpdateSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof equipmentUpdateSchema>;
const result = await updateEquipment(prisma, req.params.id, data);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/equipment/{id}:
* delete:
* summary: Delete an equipment catalog entry (admin)
* tags: [Equipment]
* responses:
* 204: { description: Deleted }
* 404: { description: Not found }
*/
router.delete('/:id', async (req, res, next) => {
try {
await deleteEquipment(prisma, req.params.id);
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,29 @@
import { Router } from 'express';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { listEquipment } from '../services/equipment.js';
export function createEquipmentPublicRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /equipment:
* get:
* summary: List the equipment (machine/device) catalog
* tags: [Equipment]
* responses:
* 200: { description: OK }
*/
router.get('/', async (_req, res, next) => {
try {
const result = await listEquipment(prisma);
res.json(result);
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,48 @@
import { Router } from 'express';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { getExercisePool, listExercisePool } from '../services/exercisePool.js';
export function createExercisePoolRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /exercises:
* get:
* summary: Exercise pool (MVP: full built-in pool, no gym equipment filtering)
* tags: [Exercises]
* responses:
* 200: { description: OK }
*/
router.get('/', async (_req, res, next) => {
try {
const result = await listExercisePool(prisma);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /exercises/{id}:
* get:
* summary: Exercise details
* tags: [Exercises]
* responses:
* 200: { description: OK }
* 404: { description: Not found }
*/
router.get('/:id', async (req, res, next) => {
try {
const result = await getExercisePool(prisma, req.params.id);
res.json(result);
} catch (e) {
next(e);
}
});
return router;
}

139
api/src/routes/exercises.ts Normal file
View File

@@ -0,0 +1,139 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate, requireAdmin } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import {
createExercise,
deleteExercise,
getExercise,
listExercises,
updateExercise,
} from '../services/exercises.js';
const muscleArraySchema = z.array(z.string().min(1).max(50)).max(20);
const exerciseSchema = z.object({
name: z.string().min(1).max(100),
primaryMuscle: z.string().min(1).max(50),
secondaryMuscles: muscleArraySchema.optional(),
description: z.string().max(2000).nullable().optional(),
howTo: z.string().max(2000).nullable().optional(),
commonMistakes: z.string().max(2000).nullable().optional(),
difficulty: z.number().int().min(1).max(10).optional(),
equipmentIds: z.array(z.string().min(1)).max(50).optional(),
});
const exerciseUpdateSchema = z.object({
name: z.string().min(1).max(100).optional(),
primaryMuscle: z.string().min(1).max(50).optional(),
secondaryMuscles: muscleArraySchema.optional(),
description: z.string().max(2000).nullable().optional(),
howTo: z.string().max(2000).nullable().optional(),
commonMistakes: z.string().max(2000).nullable().optional(),
difficulty: z.number().int().min(1).max(10).optional(),
equipmentIds: z.array(z.string().min(1)).max(50).optional(),
});
export function createExerciseRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma), requireAdmin);
/**
* @openapi
* /admin/exercises:
* get:
* summary: List exercise types with linked equipment (admin)
* tags: [Exercises]
* responses:
* 200: { description: OK }
*/
router.get('/', async (_req, res, next) => {
try {
const result = await listExercises(prisma);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/exercises:
* post:
* summary: Create an exercise type (admin)
* tags: [Exercises]
* responses:
* 201: { description: Created }
*/
router.post('/', validate(exerciseSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof exerciseSchema>;
const result = await createExercise(prisma, data);
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/exercises/{id}:
* get:
* summary: Get an exercise type with linked equipment (admin)
* tags: [Exercises]
* responses:
* 200: { description: OK }
* 404: { description: Not found }
*/
router.get('/:id', async (req, res, next) => {
try {
const result = await getExercise(prisma, req.params.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/exercises/{id}:
* patch:
* summary: Update an exercise type (admin). equipmentIds replaces the linked set.
* tags: [Exercises]
* responses:
* 200: { description: OK }
* 404: { description: Not found }
*/
router.patch('/:id', validate(exerciseUpdateSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof exerciseUpdateSchema>;
const result = await updateExercise(prisma, req.params.id, data);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /admin/exercises/{id}:
* delete:
* summary: Delete an exercise type (admin). Fails if used in plans.
* tags: [Exercises]
* responses:
* 204: { description: Deleted }
* 404: { description: Not found }
* 409: { description: Used in plans }
*/
router.delete('/:id', async (req, res, next) => {
try {
await deleteExercise(prisma, req.params.id);
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,29 @@
import { Router } from 'express';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { listFocusAreas } from '../services/focusAreas.js';
export function createFocusAreaRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /focus-areas:
* get:
* summary: Catalog of training focus areas to choose priorities/exclusions from
* tags: [FocusAreas]
* responses:
* 200: { description: OK }
*/
router.get('/', async (_req, res, next) => {
try {
const result = await listFocusAreas(prisma);
res.json(result);
} catch (e) {
next(e);
}
});
return router;
}

910
api/src/routes/gyms.ts Normal file
View File

@@ -0,0 +1,910 @@
import fs from 'node:fs';
import path from 'node:path';
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import {
acceptGymInvitation,
addEquipment,
addGymPhotos,
canManageGym,
createGym,
createGymClaim,
createOwnedGymException,
declineGymInvitation,
deleteGymPhoto,
deleteOwnedGym,
deleteOwnedGymException,
getGymPublic,
joinGym,
listAllGyms,
listGymInvitations,
listMyGymClaims,
listOwnedGymExceptions,
listUserGyms,
listVirtualGyms,
rateGym,
removeEquipment,
searchGymInvitees,
sendGymInvitation,
setGymPhotoCover,
updateEquipmentQuantity,
updateOwnedGym,
withdrawGymClaim,
withdrawGymInvitation,
} from '../services/gyms.js';
import { availabilitySchema } from './me.js';
import type { Availability } from '../services/me.js';
import { logActivity } from '../services/audit.js';
import { config } from '../config.js';
import {
MAX_CLAIM_FILES,
MAX_PHOTO_FILES,
claimUpload,
gymPhotoUpload,
photoUploadDir,
removeTmpFiles,
} from '../lib/uploads.js';
import { badRequest, forbidden, notFound } from '../lib/errors.js';
const createGymSchema = z.object({
name: z.string().min(1).max(200),
location: z.string().max(500).nullable().optional(),
availability: availabilitySchema,
capacity: z.number().int().positive().max(100000).nullable().optional(),
kind: z.enum(['VIRTUAL', 'REAL']).optional(),
isPrivate: z.boolean().optional(),
});
const updateGymSchema = createGymSchema.partial().omit({ kind: true });
const rateGymSchema = z.object({
vote: z.enum(['UP', 'DOWN']),
});
/** Multipart fields arrive as strings (multer) — gymAvailability is a JSON string. */
const gymClaimSchema = z.object({
gymId: z.string().min(1).optional(),
description: z.string().min(1).max(5000),
companyName: z.string().max(200).optional(),
nip: z.string().regex(/^\d{10}$/).optional(),
phone: z.string().max(20).optional(),
email: z.string().email().max(200).optional(),
address: z.string().max(500).optional(),
gymName: z.string().min(1).max(200).optional(),
gymLocation: z.string().max(500).optional(),
gymAvailability: z.string().optional(),
gymCapacity: z.coerce.number().int().positive().max(100000).optional(),
});
const gymInvitationSchema = z.object({
gymId: z.string().min(1),
userId: z.string().min(1),
});
const gymInviteeSearchSchema = z.object({
gymId: z.string().min(1),
firstName: z.string().min(1).max(100),
lastName: z.string().min(1).max(100),
});
const gymExceptionSchema = z.object({
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
availability: z
.object({
start: z.string().regex(/^\d{2}:\d{2}$/),
end: z.string().regex(/^\d{2}:\d{2}$/),
})
.nullable()
.optional(),
});
const equipmentSchema = z.object({
equipmentId: z.string().min(1),
quantity: z.number().int().min(1).max(10000).optional(),
});
const equipmentQuantitySchema = z.object({
quantity: z.number().int().min(1).max(10000),
});
export function createGymRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /gyms:
* get:
* summary: User's gyms (memberships)
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
router.get('/', async (req, res, next) => {
try {
const result = await listUserGyms(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/all:
* get:
* summary: All gyms (for selecting an existing gym)
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
router.get('/all', async (_req, res, next) => {
try {
const result = await listAllGyms(prisma);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms:
* post:
* summary: Create a gym (creator becomes its OWNER; non-admins: VIRTUAL only, location required)
* tags: [Gyms]
* responses:
* 201: { description: Created }
* 400: { description: Validation failed (e.g. missing location for VIRTUAL) }
* 403: { description: Non-admin requested kind=REAL }
*/
router.post('/', validate(createGymSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof createGymSchema>;
const result = await createGym(prisma, req.user!.id, data, req.user!.isAdmin);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.created',
entityType: 'gym',
entityId: result.gym.id,
details: { name: result.gym.name, kind: result.gym.kind },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/virtual:
* get:
* summary: Public virtual gyms (with ratings + claim status) and own private virtual gyms
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
router.get('/virtual', async (req, res, next) => {
try {
const result = await listVirtualGyms(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/claims:
* post:
* summary: Submit a gym claim (multipart; verification of a virtual gym or a new real gym)
* tags: [Gyms]
* responses:
* 201: { description: Created }
* 400: { description: Validation failed (fields or files) }
* 404: { description: Gym not found }
* 409: { description: Gym is not virtual / pending claim already exists }
*/
router.post(
'/claims',
(req, res, next) =>
claimUpload.array('files', MAX_CLAIM_FILES)(req, res, (err) => {
if (err) {
const message =
err.code === 'LIMIT_FILE_SIZE'
? 'File too large (max 5 MB)'
: err.code === 'LIMIT_FILE_COUNT'
? 'Too many files (max 5)'
: err.message;
return next(badRequest(message));
}
next();
}),
validate(gymClaimSchema),
async (req, res, next) => {
try {
const body = req.body as z.infer<typeof gymClaimSchema>;
let gymAvailability: Availability | null | undefined;
if (body.gymAvailability) {
try {
gymAvailability = availabilitySchema.parse(JSON.parse(body.gymAvailability));
} catch {
throw badRequest('Invalid gym availability');
}
}
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
originalName: f.originalname,
mimeType: f.mimetype,
sizeBytes: f.size,
path: f.path,
}));
const result = await createGymClaim(
prisma,
req.user!.id,
{
gymId: body.gymId,
description: body.description,
companyName: body.companyName,
nip: body.nip,
phone: body.phone,
email: body.email,
address: body.address,
gymName: body.gymName,
gymLocation: body.gymLocation,
gymAvailability,
gymCapacity: body.gymCapacity,
},
files,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.claim.created',
entityType: 'gym-claim',
entityId: result.claim.id,
details: { gymId: result.claim.gymId, type: result.claim.type },
});
res.status(201).json(result);
} catch (e) {
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
next(e);
}
},
);
/**
* @openapi
* /gyms/claims:
* get:
* summary: The user's own gym claims (all statuses)
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
router.get('/claims', async (req, res, next) => {
try {
const result = await listMyGymClaims(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/claims/{claimId}:
* delete:
* summary: Withdraw the user's own PENDING gym claim
* tags: [Gyms]
* responses:
* 204: { description: Withdrawn }
* 403: { description: Not the claim author }
* 409: { description: Claim is not pending }
*/
router.delete('/claims/:claimId', async (req, res, next) => {
try {
await withdrawGymClaim(prisma, req.user!.id, req.params.claimId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.claim.withdrawn',
entityType: 'gym-claim',
entityId: req.params.claimId,
});
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations:
* post:
* summary: Invite a user to a private virtual gym (owner only)
* tags: [Gyms]
* responses:
* 201: { description: Invitation sent }
* 400: { description: Cannot invite yourself }
* 403: { description: Not the gym owner }
* 404: { description: Gym or user not found }
* 409: { description: Gym not private virtual / already a member / pending invitation exists }
*/
router.post('/invitations', validate(gymInvitationSchema), async (req, res, next) => {
try {
const { gymId, userId } = req.body as z.infer<typeof gymInvitationSchema>;
const result = await sendGymInvitation(prisma, req.user!.id, gymId, userId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invited',
entityType: 'gym-invitation',
entityId: result.invitation.id,
details: { gymId, userId },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations:
* get:
* summary: The user's pending gym invitations (sent and received)
* tags: [Gyms]
* responses:
* 200: { description: OK }
*/
router.get('/invitations', async (req, res, next) => {
try {
const result = await listGymInvitations(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations/search:
* get:
* summary: Search users to invite to a private virtual gym (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 404: { description: Gym not found }
*/
router.get(
'/invitations/search',
validate(gymInviteeSearchSchema, 'query'),
async (req, res, next) => {
try {
const q = req.query as z.infer<typeof gymInviteeSearchSchema>;
const result = await searchGymInvitees(
prisma,
req.user!.id,
q.gymId,
q.firstName,
q.lastName,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/invitations/{invitationId}/accept:
* post:
* summary: Accept a gym invitation (invited user only) → MEMBER
* tags: [Gyms]
* responses:
* 200: { description: Accepted }
* 403: { description: Not the invited user }
* 410: { description: Invitation expired }
*/
router.post('/invitations/:invitationId/accept', async (req, res, next) => {
try {
const result = await acceptGymInvitation(prisma, req.user!.id, req.params.invitationId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invitation.accepted',
entityType: 'gym-invitation',
entityId: req.params.invitationId,
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations/{invitationId}/decline:
* post:
* summary: Decline a gym invitation (invited user only)
* tags: [Gyms]
* responses:
* 200: { description: Declined }
* 403: { description: Not the invited user }
* 410: { description: Invitation expired }
*/
router.post('/invitations/:invitationId/decline', async (req, res, next) => {
try {
const result = await declineGymInvitation(prisma, req.user!.id, req.params.invitationId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invitation.declined',
entityType: 'gym-invitation',
entityId: req.params.invitationId,
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/invitations/{invitationId}:
* delete:
* summary: Withdraw a pending gym invitation (sender only)
* tags: [Gyms]
* responses:
* 204: { description: Withdrawn }
* 403: { description: Not the sender }
* 409: { description: Invitation is not pending }
*/
router.delete('/invitations/:invitationId', async (req, res, next) => {
try {
await withdrawGymInvitation(prisma, req.user!.id, req.params.invitationId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.invitation.withdrawn',
entityType: 'gym-invitation',
entityId: req.params.invitationId,
});
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}:
* get:
* summary: Public gym detail (REAL visible to all logged-in users; VIRTUAL to managers)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym, roles, isAdmin } }
* 403: { description: VIRTUAL gym and the caller is not a manager }
* 404: { description: Gym not found }
*/
router.get('/:gymId', async (req, res, next) => {
try {
const result = await getGymPublic(prisma, req.user!.id, req.user!.isAdmin, req.params.gymId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/photos:
* post:
* summary: Add photos to a REAL gym's gallery (owner or admin; multipart field `photos`)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym } }
* 400: { description: Validation failed (file type/size/count or photo limit) }
* 403: { description: Not the gym owner and not an admin }
* 404: { description: Gym not found }
* 409: { description: Gym is not REAL }
*/
router.post(
'/:gymId/photos',
(req, res, next) =>
gymPhotoUpload.array('photos', MAX_PHOTO_FILES)(req, res, (err) => {
if (err) {
const message =
err.code === 'LIMIT_FILE_SIZE'
? 'File too large (max 5 MB)'
: err.code === 'LIMIT_FILE_COUNT'
? 'Too many files (max 10)'
: err.message;
return next(badRequest(message));
}
next();
}),
async (req, res, next) => {
try {
const files = ((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({
mimeType: f.mimetype,
sizeBytes: f.size,
path: f.path,
}));
const result = await addGymPhotos(
prisma,
req.user!.id,
req.user!.isAdmin,
req.params.gymId,
files,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photos.added',
entityType: 'gym',
entityId: req.params.gymId,
details: { count: files.length },
});
res.json(result);
} catch (e) {
removeTmpFiles(((req.files as Express.Multer.File[] | undefined) ?? []).map((f) => ({ path: f.path })));
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/photos/{photoId}:
* delete:
* summary: Remove a photo from a gym's gallery (owner or admin)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym } }
* 403: { description: Not the gym owner and not an admin }
* 404: { description: Photo not found }
*/
router.delete('/:gymId/photos/:photoId', async (req, res, next) => {
try {
const result = await deleteGymPhoto(
prisma,
req.user!.id,
req.user!.isAdmin,
req.params.gymId,
req.params.photoId,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photo.deleted',
entityType: 'gym',
entityId: req.params.gymId,
details: { photoId: req.params.photoId },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/photos/{photoId}/cover:
* patch:
* summary: Set a photo as the gallery cover (owner or admin)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { gym } }
* 403: { description: Not the gym owner and not an admin }
* 404: { description: Photo not found }
*/
router.patch('/:gymId/photos/:photoId/cover', async (req, res, next) => {
try {
const result = await setGymPhotoCover(
prisma,
req.user!.id,
req.user!.isAdmin,
req.params.gymId,
req.params.photoId,
);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.photo.cover',
entityType: 'gym',
entityId: req.params.gymId,
details: { photoId: req.params.photoId },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/photos/{photoId}:
* get:
* summary: Serve a gym photo (REAL visible to all logged-in users; VIRTUAL to managers)
* tags: [Gyms]
* responses:
* 200: { description: Image bytes with the stored Content-Type }
* 403: { description: VIRTUAL gym and the caller is not a manager }
* 404: { description: Photo not found or file missing }
*/
router.get('/:gymId/photos/:photoId', async (req, res, next) => {
try {
const { gymId, photoId } = req.params;
const photo = await prisma.gymPhoto.findUnique({ where: { id: photoId } });
if (!photo || photo.gymId !== gymId) throw notFound('Photo not found');
const gym = await prisma.gym.findUnique({ where: { id: gymId }, select: { kind: true } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'REAL' && !(await canManageGym(prisma, gymId, req.user!.id, req.user!.isAdmin)))
throw forbidden('You do not have access to this gym');
const filePath = path.join(photoUploadDir(gymId), photo.storedName);
if (!fs.existsSync(filePath)) throw notFound('Photo file not found');
res.type(photo.mimeType);
await new Promise<void>((resolve, reject) => {
res.sendFile(filePath, (err) => (err ? reject(err) : resolve()));
});
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/join:
* post:
* summary: Join an existing gym (MEMBER membership)
* tags: [Gyms]
* responses:
* 201: { description: Joined }
* 409: { description: Already a member }
*/
router.post('/:gymId/join', async (req, res, next) => {
try {
const result = await joinGym(prisma, req.user!.id, req.params.gymId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.joined',
entityType: 'gym',
entityId: req.params.gymId,
details: { name: result.membership.name },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/rate:
* post:
* summary: Thumb vote on a public virtual gym (toggle: same vote again removes it)
* tags: [Gyms]
* responses:
* 200: { description: OK, returns { vote, up, down } }
* 403: { description: The gym owner cannot rate their own gym }
* 404: { description: Gym not found }
* 409: { description: Gym is not a public virtual gym }
*/
router.post('/:gymId/rate', validate(rateGymSchema), async (req, res, next) => {
try {
const { vote } = req.body as z.infer<typeof rateGymSchema>;
const result = await rateGym(prisma, req.user!.id, req.params.gymId, vote);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/equipment:
* post:
* summary: Add a catalog equipment item to a gym with a quantity (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 404: { description: Equipment not found }
* 409: { description: Equipment already exists (update its quantity instead) }
*/
router.post(
'/:gymId/equipment',
validate(equipmentSchema),
async (req, res, next) => {
try {
const { equipmentId, quantity } = req.body as z.infer<typeof equipmentSchema>;
const result = await addEquipment(
prisma,
req.params.gymId,
req.user!.id,
equipmentId,
quantity ?? 1,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/equipment/{equipmentId}:
* patch:
* summary: Change the quantity of a gym's equipment item (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 400: { description: Equipment not in the gym }
*/
router.patch(
'/:gymId/equipment/:equipmentId',
validate(equipmentQuantitySchema),
async (req, res, next) => {
try {
const { quantity } = req.body as z.infer<typeof equipmentQuantitySchema>;
const result = await updateEquipmentQuantity(
prisma,
req.params.gymId,
req.user!.id,
req.params.equipmentId,
quantity,
);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/equipment/{equipmentId}:
* delete:
* summary: Remove a catalog equipment item from a gym (owner only)
* tags: [Gyms]
* responses:
* 204: { description: Removed }
* 403: { description: Not the gym owner }
*/
router.delete('/:gymId/equipment/:equipmentId', async (req, res, next) => {
try {
await removeEquipment(prisma, req.params.gymId, req.user!.id, req.params.equipmentId);
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}:
* patch:
* summary: Update a gym (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
* 404: { description: Gym not found }
*/
router.patch('/:gymId', validate(updateGymSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof updateGymSchema>;
const result = await updateOwnedGym(prisma, req.params.gymId, req.user!.id, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.updated',
entityType: 'gym',
entityId: req.params.gymId,
details: { name: result.gym.name },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}:
* delete:
* summary: Delete a gym (owner only). Memberships are removed; user plans are kept.
* tags: [Gyms]
* responses:
* 204: { description: Deleted }
* 403: { description: Not the gym owner }
* 404: { description: Gym not found }
*/
router.delete('/:gymId', async (req, res, next) => {
try {
const result = await deleteOwnedGym(prisma, req.params.gymId, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'gym.deleted',
entityType: 'gym',
entityId: req.params.gymId,
details: { name: result.name },
});
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/exceptions:
* get:
* summary: List a gym's schedule exceptions (owner only)
* tags: [Gyms]
* responses:
* 200: { description: OK }
* 403: { description: Not the gym owner }
*/
router.get('/:gymId/exceptions', async (req, res, next) => {
try {
const result = await listOwnedGymExceptions(prisma, req.params.gymId, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /gyms/{gymId}/exceptions:
* post:
* summary: Add a one-off schedule exception (owner only)
* tags: [Gyms]
* responses:
* 201: { description: Created }
* 403: { description: Not the gym owner }
* 409: { description: Exception already exists for this date }
*/
router.post(
'/:gymId/exceptions',
validate(gymExceptionSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof gymExceptionSchema>;
const result = await createOwnedGymException(prisma, req.params.gymId, req.user!.id, {
date: data.date,
availability: data.availability ?? null,
});
res.status(201).json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /gyms/{gymId}/exceptions/{exceptionId}:
* delete:
* summary: Remove a schedule exception (owner only)
* tags: [Gyms]
* responses:
* 204: { description: Removed }
* 403: { description: Not the gym owner }
* 404: { description: Exception not found }
*/
router.delete('/:gymId/exceptions/:exceptionId', async (req, res, next) => {
try {
await deleteOwnedGymException(
prisma,
req.params.gymId,
req.user!.id,
req.params.exceptionId,
);
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

357
api/src/routes/me.ts Normal file
View File

@@ -0,0 +1,357 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import {
addCircumference,
addWeight,
deleteCircumference,
deleteWeight,
getBodyParameters,
getHistory,
getProfile,
updateProfile,
} from '../services/me.js';
import { getFocusChain } from '../services/focusChain.js';
import { getActiveSession } from '../services/sessions.js';
import { addMyComment, deleteMyComment } from '../services/comments.js';
import { getExerciseProgress } from '../services/exerciseProgress.js';
import { logActivity } from '../services/audit.js';
const muscleArraySchema = z.array(z.string().min(1).max(50)).max(20);
export const dayAvailabilitySchema = z.object({
start: z.string().regex(/^\d{2}:\d{2}$/),
end: z.string().regex(/^\d{2}:\d{2}$/),
});
export const availabilitySchema = z.array(dayAvailabilitySchema.nullable()).max(7).nullish();
export const socialMediaEntrySchema = z.object({
platform: z.enum(['INSTAGRAM', 'TIKTOK', 'YOUTUBE', 'FACEBOOK', 'X', 'OTHER']),
url: z.string().url().max(500),
label: z.string().max(50).optional(),
});
const profileSchema = z.object({
firstName: z.string().min(1).max(100).nullable().optional(),
lastName: z.string().min(1).max(100).nullable().optional(),
nickname: z.string().min(1).max(50).nullable().optional(),
socialMedia: z.array(socialMediaEntrySchema).max(20).nullable().optional(),
age: z.number().int().min(10).max(100).nullable().optional(),
heightCm: z.number().positive().max(250).nullable().optional(),
phone: z.string().min(5).max(20).nullable().optional(),
availability: availabilitySchema,
priorities: z.string().max(2000).nullable().optional(),
exclusions: z.string().max(2000).nullable().optional(),
developMuscles: muscleArraySchema.optional(),
canDoMuscles: muscleArraySchema.optional(),
difficultMuscles: muscleArraySchema.optional(),
avoidMuscles: muscleArraySchema.optional(),
});
const weightSchema = z.object({
value: z.number().positive().max(500),
date: z.string().datetime({ offset: true }).optional(),
});
const circumferenceSchema = z.object({
name: z.string().min(1).max(100),
value: z.number().positive().max(300),
date: z.string().datetime({ offset: true }).optional(),
});
const myCommentSchema = z.object({
body: z.string().min(1).max(1000),
sessionId: z.string().min(1),
sessionExerciseId: z.string().min(1).optional(),
});
export function createMeRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /me:
* get:
* summary: Current user profile + gym memberships
* tags: [Profile]
* responses:
* 200: { description: OK }
*/
router.get('/', async (req, res, next) => {
try {
const result = await getProfile(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/active-session:
* get:
* summary: Active (IN_PROGRESS) training session of the current user, if any
* tags: [Sessions]
* responses:
* 200: { description: OK }
*/
router.get('/active-session', async (req, res, next) => {
try {
const result = await getActiveSession(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/focus-chain:
* get:
* summary: Causal chain — selected priority/exclusion muscles linked to active plan exercises
* tags: [Profile]
* responses:
* 200: { description: OK }
*/
router.get('/focus-chain', async (req, res, next) => {
try {
const result = await getFocusChain(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me:
* patch:
* summary: Update profile (personal data, priorities, exclusions, available time)
* tags: [Profile]
* responses:
* 200: { description: OK }
*/
router.patch('/', validate(profileSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof profileSchema>;
const result = await updateProfile(prisma, req.user!.id, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'profile.updated',
entityType: 'user',
entityId: req.user!.id,
details: { fields: Object.keys(data) },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/body-parameters:
* get:
* summary: Body parameters over time (weight history + circumference series)
* tags: [Profile]
* responses:
* 200: { description: OK }
*/
router.get('/body-parameters', async (req, res, next) => {
try {
const result = await getBodyParameters(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/history:
* get:
* summary: Training history — recent sessions with exercises and set details (actual + planned)
* tags: [Profile]
* responses:
* 200: { description: OK }
*/
router.get('/history', async (req, res, next) => {
try {
const result = await getHistory(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/exercise-progress:
* get:
* summary: Per-exercise progress (1RM Epley + volume per completed session)
* tags: [Profile]
* responses:
* 200: { description: OK }
*/
router.get('/exercise-progress', async (req, res, next) => {
try {
const result = await getExerciseProgress(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/comments:
* post:
* summary: Comment on my own session / exercise
* tags: [Profile]
* responses:
* 201: { description: Created }
* 400: { description: Invalid session anchor }
*/
router.post('/comments', validate(myCommentSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof myCommentSchema>;
const result = await addMyComment(prisma, req.user!.id, data);
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/comments/{commentId}:
* delete:
* summary: Delete my own comment
* tags: [Profile]
* responses:
* 204: { description: Deleted }
* 404: { description: Comment not found }
*/
router.delete('/comments/:commentId', async (req, res, next) => {
try {
await deleteMyComment(prisma, req.user!.id, req.params.commentId);
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/body-parameters/weight:
* post:
* summary: Add weight measurement
* tags: [Profile]
* responses:
* 201: { description: Created }
*/
router.post('/body-parameters/weight', validate(weightSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof weightSchema>;
const result = await addWeight(prisma, req.user!.id, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'weight.added',
entityType: 'user',
entityId: req.user!.id,
details: { value: data.value },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/body-parameters/circumference:
* post:
* summary: Add circumference measurement (name + value)
* tags: [Profile]
* responses:
* 201: { description: Created }
*/
router.post(
'/body-parameters/circumference',
validate(circumferenceSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof circumferenceSchema>;
const result = await addCircumference(prisma, req.user!.id, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'circumference.added',
entityType: 'user',
entityId: req.user!.id,
details: { name: data.name, value: data.value },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /me/body-parameters/weight/{id}:
* delete:
* summary: Delete a weight measurement
* tags: [Profile]
* responses:
* 204: { description: Deleted }
* 404: { description: Not found }
*/
router.delete('/body-parameters/weight/:id', async (req, res, next) => {
try {
const result = await deleteWeight(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'weight.removed',
entityType: 'user',
entityId: req.user!.id,
details: { value: result.value },
});
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /me/body-parameters/circumference/{id}:
* delete:
* summary: Delete a circumference measurement
* tags: [Profile]
* responses:
* 204: { description: Deleted }
* 404: { description: Not found }
*/
router.delete('/body-parameters/circumference/:id', async (req, res, next) => {
try {
const result = await deleteCircumference(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'circumference.removed',
entityType: 'user',
entityId: req.user!.id,
details: { name: result.name, value: result.value },
});
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

101
api/src/routes/messages.ts Normal file
View File

@@ -0,0 +1,101 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import {
deleteMessage,
getConversation,
listConversations,
sendMessage,
} from '../services/messages.js';
const sendSchema = z.object({
body: z.string().min(1).max(1000),
sessionId: z.string().min(1).optional(),
sessionExerciseId: z.string().min(1).optional(),
});
export function createMessageRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /messages/conversations:
* get:
* summary: My ACTIVE coaching relations as conversations (last message + unread count)
* tags: [Messages]
* responses:
* 200: { description: OK }
*/
router.get('/conversations', async (req, res, next) => {
try {
const result = await listConversations(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /messages/conversations/{coachingId}:
* get:
* summary: Thread of an ACTIVE relation (either party) + read-mark
* tags: [Messages]
* responses:
* 200: { description: OK }
* 404: { description: Not a party of the relation or not ACTIVE }
*/
router.get('/conversations/:coachingId', async (req, res, next) => {
try {
const result = await getConversation(prisma, req.user!.id, req.params.coachingId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /messages/conversations/{coachingId}:
* post:
* summary: Send a message (optional attachment: completed trainee session + exercise)
* tags: [Messages]
* responses:
* 201: { description: Created }
* 400: { description: Invalid attachment }
* 404: { description: Not a party of the relation or not ACTIVE }
*/
router.post('/conversations/:coachingId', validate(sendSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof sendSchema>;
const result = await sendMessage(prisma, req.user!.id, req.params.coachingId, data);
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /messages/{id}:
* delete:
* summary: Delete a message (author only)
* tags: [Messages]
* responses:
* 204: { description: Deleted }
* 404: { description: Message not found or not the author }
*/
router.delete('/:id', async (req, res, next) => {
try {
await deleteMessage(prisma, req.user!.id, req.params.id);
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

View File

@@ -0,0 +1,57 @@
import { z } from 'zod';
export const planSetSchema = z.object({
index: z.number().int().min(0),
reps: z.number().int().positive().max(1000).nullable().optional(),
loadKg: z.number().positive().max(1000).nullable().optional(),
restSec: z.number().int().positive().max(3600).nullable().optional(),
rir: z.number().int().min(0).max(10).nullable().optional(),
difficulty: z.number().int().min(1).max(5).nullable().optional(),
cardioBpm: z.number().int().positive().max(300).nullable().optional(),
timeSec: z.number().int().positive().max(86400).nullable().optional(),
speed: z.number().positive().max(100).nullable().optional(),
});
const planExerciseSchema = z.object({
exerciseId: z.string().min(1),
order: z.number().int().min(0),
sets: z.array(planSetSchema).min(1),
});
const planDaySchema = z.object({
dayOfWeek: z.number().int().min(1).max(7),
exercises: z.array(planExerciseSchema),
});
const planWeekSchema = z.object({
index: z.number().int().min(0),
days: z.array(planDaySchema),
});
const planBaseSchema = z.object({
title: z.string().min(1).max(200),
weeksCount: z.number().int().min(1).max(8),
weeks: z.array(planWeekSchema),
});
export const createPlanSchema = planBaseSchema
.extend({
// Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku.
startDate: z
.string()
.refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date')
.optional(),
})
.refine((d) => d.weeks.length === d.weeksCount, {
message: 'weeks must have exactly weeksCount entries',
});
export const updatePlanSchema = planBaseSchema.refine((d) => d.weeks.length === d.weeksCount, {
message: 'weeks must have exactly weeksCount entries',
});
export const activateSchema = z.object({
startDate: z
.string()
.refine((v) => !Number.isNaN(new Date(v).getTime()), 'Invalid date'),
});

219
api/src/routes/plans.ts Normal file
View File

@@ -0,0 +1,219 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import {
abandonPlan,
activatePlan,
completePlan,
createPlan,
deletePlan,
getPlan,
listPlans,
updatePlan,
} from '../services/plans.js';
import { logActivity } from '../services/audit.js';
import { activateSchema, createPlanSchema, updatePlanSchema } from './plans-schemas.js';
export function createPlanRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /plans:
* get:
* summary: User's plans
* tags: [Plans]
* responses:
* 200: { description: OK }
*/
router.get('/', async (req, res, next) => {
try {
const result = await listPlans(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /plans:
* post:
* summary: Create plan. Structure: weeks -> days (dayOfWeek) -> exercises -> sets.
* Optional startDate (a Monday) creates and activates the plan in one step.
* tags: [Plans]
* responses:
* 201: { description: Created }
* 400: { description: Validation error / start date not a Monday / start week in the past }
* 409: { description: User already has an active plan }
*/
router.post('/', validate(createPlanSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof createPlanSchema>;
const result = await createPlan(prisma, req.user!.id, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.created',
entityType: 'plan',
entityId: result.plan.id,
details: { title: result.plan.title },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /plans/{id}:
* get:
* summary: Plan details (weeks -> days -> exercises -> sets)
* tags: [Plans]
* responses:
* 200: { description: OK }
* 404: { description: Not found }
*/
router.get('/:id', async (req, res, next) => {
try {
const result = await getPlan(prisma, req.params.id, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /plans/{id}:
* patch:
* summary: Replace plan structure (draft only)
* tags: [Plans]
* responses:
* 200: { description: OK }
*/
router.patch('/:id', validate(updatePlanSchema), async (req, res, next) => {
try {
const data = req.body as z.infer<typeof updatePlanSchema>;
const result = await updatePlan(prisma, req.params.id, req.user!.id, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.updated',
entityType: 'plan',
entityId: req.params.id,
details: { title: data.title },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /plans/{id}:
* delete:
* summary: Delete plan (draft only)
* tags: [Plans]
* responses:
* 204: { description: Deleted }
*/
router.delete('/:id', async (req, res, next) => {
try {
const result = await deletePlan(prisma, req.params.id, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.deleted',
entityType: 'plan',
entityId: req.params.id,
details: { title: result.title },
});
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /plans/{id}/activate:
* post:
* summary: Activate plan. startDate must be a Monday (first day of week)
* of the current or a future week. Training day dates are computed automatically.
* tags: [Plans]
* responses:
* 200: { description: OK }
* 409: { description: User already has an active plan }
*/
router.post('/:id/activate', validate(activateSchema), async (req, res, next) => {
try {
const { startDate } = req.body as z.infer<typeof activateSchema>;
const result = await activatePlan(prisma, req.params.id, req.user!.id, startDate);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.activated',
entityType: 'plan',
entityId: req.params.id,
details: { title: result.title, startDate },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /plans/{id}/abandon:
* post:
* summary: Abandon plan (draft/active)
* tags: [Plans]
* responses:
* 200: { description: OK }
*/
router.post('/:id/abandon', async (req, res, next) => {
try {
const result = await abandonPlan(prisma, req.params.id, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.abandoned',
entityType: 'plan',
entityId: req.params.id,
details: { title: result.title },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /plans/{id}/complete:
* post:
* summary: Manually archive plan (mark as completed)
* tags: [Plans]
* responses:
* 200: { description: OK }
*/
router.post('/:id/complete', async (req, res, next) => {
try {
const result = await completePlan(prisma, req.params.id, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.completed',
entityType: 'plan',
entityId: req.params.id,
details: { title: result.title },
});
res.json(result);
} catch (e) {
next(e);
}
});
return router;
}

262
api/src/routes/sessions.ts Normal file
View File

@@ -0,0 +1,262 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import {
abandonSession,
addExercise,
addSet,
completeSession,
deleteSet,
getDay,
getSession,
startSession,
updateExercise,
updateSet,
} from '../services/sessions.js';
import { logActivity } from '../services/audit.js';
const addExerciseSchema = z.object({ exerciseId: z.string().min(1) });
const updateExerciseSchema = z.object({
hidden: z.boolean().optional(),
removed: z.boolean().optional(),
});
const updateSetSchema = z.object({
reps: z.number().int().positive().max(1000).nullable().optional(),
rir: z.number().int().min(0).max(10).nullable().optional(),
difficulty: z.number().int().min(1).max(5).nullable().optional(),
note: z.string().max(2000).nullable().optional(),
});
export function createSessionRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
/**
* @openapi
* /days/{dayId}/sessions:
* post:
* summary: Start session for a planned day (initializes session exercises + sets from plan).
* Only one active session per user (across all days).
* tags: [Sessions]
* responses:
* 201: { description: Created }
* 409: { description: User already has an active session }
*/
router.post('/days/:dayId/sessions', async (req, res, next) => {
try {
const result = await startSession(prisma, req.params.dayId, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'session.started',
entityType: 'session',
entityId: result.sessionId,
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /days/{dayId}:
* get:
* summary: Training day details (status, date, sessions)
* tags: [Sessions]
* responses:
* 200: { description: OK }
* 404: { description: Not found }
*/
router.get('/days/:dayId', async (req, res, next) => {
try {
const result = await getDay(prisma, req.params.dayId, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /sessions/{id}:
* get:
* summary: Session details (exercises -> sets, planned parameters as parent)
* tags: [Sessions]
* responses:
* 200: { description: OK }
*/
router.get('/sessions/:id', async (req, res, next) => {
try {
const result = await getSession(prisma, req.params.id, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /sessions/{id}/exercises:
* post:
* summary: Add exercise to session (SessionSet without PlanSet — data kept for restore)
* tags: [Sessions]
* responses:
* 201: { description: Created }
*/
router.post(
'/sessions/:id/exercises',
validate(addExerciseSchema),
async (req, res, next) => {
try {
const { exerciseId } = req.body as z.infer<typeof addExerciseSchema>;
const result = await addExercise(prisma, req.params.id, req.user!.id, exerciseId);
res.status(201).json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /sessions/exercises/{id}:
* patch:
* summary: Hide or remove exercise from session (data kept for restore)
* tags: [Sessions]
* responses:
* 200: { description: OK }
*/
router.patch(
'/sessions/exercises/:id',
validate(updateExerciseSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof updateExerciseSchema>;
const result = await updateExercise(prisma, req.params.id, req.user!.id, data);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /sessions/exercises/{id}/sets:
* post:
* summary: Add an extra (bonus) set. Only when all planned sets of the session are
* recorded and no extra set is still pending (at most one pending extra per session).
* tags: [Sessions]
* responses:
* 201: { description: Created }
* 400: { description: Norm not done or an extra set is already in progress }
*/
router.post('/sessions/exercises/:id/sets', async (req, res, next) => {
try {
const result = await addSet(prisma, req.params.id, req.user!.id);
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /sessions/sets/{id}:
* patch:
* summary: Record actual set results (reps, RIR, difficulty, note)
* tags: [Sessions]
* responses:
* 200: { description: OK }
*/
router.patch(
'/sessions/sets/:id',
validate(updateSetSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof updateSetSchema>;
const result = await updateSet(prisma, req.params.id, req.user!.id, data);
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /sessions/sets/{id}:
* delete:
* summary: Remove an extra (bonus) set (only sets without a planned counterpart)
* tags: [Sessions]
* responses:
* 200: { description: OK }
* 400: { description: Planned set or session not in progress }
* 404: { description: Not found }
*/
router.delete('/sessions/sets/:id', async (req, res, next) => {
try {
const result = await deleteSet(prisma, req.params.id, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /sessions/{id}/complete:
* post:
* summary: Complete session (requires all planned/norm sets recorded; extra sets are
* a bonus and don't block; day -> completed)
* tags: [Sessions]
* responses:
* 200: { description: OK }
* 400: { description: Session not in progress or planned sets still pending }
*/
router.post('/sessions/:id/complete', async (req, res, next) => {
try {
const result = await completeSession(prisma, req.params.id, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'session.completed',
entityType: 'session',
entityId: req.params.id,
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /sessions/{id}/abandon:
* post:
* summary: Abandon session (data kept, day -> skipped, the training cannot be executed again)
* tags: [Sessions]
* responses:
* 200: { description: OK }
* 400: { description: Session not in progress }
*/
router.post('/sessions/:id/abandon', async (req, res, next) => {
try {
const result = await abandonSession(prisma, req.params.id, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'session.abandoned',
entityType: 'session',
entityId: req.params.id,
});
res.json(result);
} catch (e) {
next(e);
}
});
return router;
}

681
api/src/routes/trainer.ts Normal file
View File

@@ -0,0 +1,681 @@
import { Router } from 'express';
import { z } from 'zod';
import type { AppDeps } from '../deps.js';
import { authenticate, requireTrainer } from '../middleware/auth.js';
import { validate } from '../middleware/validate.js';
import { badRequest } from '../lib/errors.js';
import {
acceptInvitation,
archiveTrainee,
assertActiveTrainee,
declineInvitation,
getTraineeCalendar,
getTraineeDetail,
getTraineeHistory,
getTraineeMoves,
getTraineeReport,
listInvitations,
listTrainees,
searchUsers,
sendInvitation,
withdrawInvitation,
} from '../services/trainer.js';
import { addTraineeComment, deleteTraineeComment } from '../services/comments.js';
import { getTraineeExerciseProgress, getTraineeLatestResults } from '../services/exerciseProgress.js';
import {
abandonPlan,
activatePlan,
completePlan,
createPlan,
deletePlan,
getPlan,
listPlans,
updatePlan,
} from '../services/plans.js';
import { activateSchema, createPlanSchema, updatePlanSchema } from './plans-schemas.js';
import { logActivity } from '../services/audit.js';
const invitationSchema = z.object({
userId: z.string().min(1),
});
const commentSchema = z.object({
body: z.string().min(1).max(1000),
sessionId: z.string().min(1).optional(),
sessionExerciseId: z.string().min(1).optional(),
});
const searchQuerySchema = z.object({
firstName: z.string().min(1).max(100),
lastName: z.string().min(1).max(100),
});
const calendarQuerySchema = z.object({
month: z
.string()
.regex(/^\d{4}-(0[1-9]|1[0-2])$/, 'Expected YYYY-MM')
.optional(),
});
export function createTrainerRoutes({ prisma }: AppDeps) {
const router = Router();
router.use(authenticate(prisma));
const trainerOnly = requireTrainer(prisma);
/**
* @openapi
* /trainer/invitations:
* get:
* summary: My pending coaching invitations (sent + received, not expired)
* tags: [Trainer]
* responses:
* 200: { description: OK }
*/
router.get('/invitations', async (req, res, next) => {
try {
const result = await listInvitations(prisma, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/invitations:
* post:
* summary: Send a coaching invitation (at least one party must be a trainer)
* tags: [Trainer]
* responses:
* 201: { description: Created }
* 400: { description: Self-invite or no trainer role }
* 404: { description: User not found }
* 409: { description: Invitation exists or pending limit reached }
*/
router.post('/invitations', validate(invitationSchema), async (req, res, next) => {
try {
const { userId } = req.body as z.infer<typeof invitationSchema>;
const result = await sendInvitation(prisma, req.user!.id, userId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.invited',
entityType: 'coaching',
entityId: result.coaching.id,
details: { targetEmail: result.targetEmail },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/invitations/{id}/accept:
* post:
* summary: Accept a coaching invitation (invited party only)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Sender cannot accept own invitation }
* 404: { description: Invitation not found }
* 409: { description: Invitation is not pending }
* 410: { description: Invitation expired }
*/
router.post('/invitations/:id/accept', async (req, res, next) => {
try {
const result = await acceptInvitation(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.accepted',
entityType: 'coaching',
entityId: result.coaching.id,
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/invitations/{id}/decline:
* post:
* summary: Decline a coaching invitation (invited party only)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Sender cannot decline own invitation }
* 404: { description: Invitation not found }
* 409: { description: Invitation is not pending }
* 410: { description: Invitation expired }
*/
router.post('/invitations/:id/decline', async (req, res, next) => {
try {
const result = await declineInvitation(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.declined',
entityType: 'coaching',
entityId: result.coaching.id,
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/invitations/{id}:
* delete:
* summary: Withdraw a pending coaching invitation (sender only)
* tags: [Trainer]
* responses:
* 204: { description: Withdrawn }
* 403: { description: Only the sender can withdraw }
* 404: { description: Invitation not found }
* 409: { description: Invitation is not pending }
*/
router.delete('/invitations/:id', async (req, res, next) => {
try {
await withdrawInvitation(prisma, req.user!.id, req.params.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.withdrawn',
entityType: 'coaching',
entityId: req.params.id,
});
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/search:
* get:
* summary: Search users by first + last name (trainer only; excludes own trainees)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Missing query parameters }
* 403: { description: Trainer role required }
*/
router.get('/search', trainerOnly, async (req, res, next) => {
try {
const parsed = searchQuerySchema.safeParse(req.query);
if (!parsed.success) throw badRequest('firstName and lastName query parameters are required');
const result = await searchUsers(prisma, req.user!.id, parsed.data.firstName, parsed.data.lastName);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees:
* get:
* summary: Active trainees with metrics (trainer only; optional ?gymId= filter)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
*/
router.get('/trainees', trainerOnly, async (req, res, next) => {
try {
const gymId = typeof req.query.gymId === 'string' ? req.query.gymId : undefined;
const result = await listTrainees(prisma, req.user!.id, gymId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}:
* delete:
* summary: Archive the trainer–trainee relation (trainer only)
* tags: [Trainer]
* responses:
* 204: { description: Archived }
* 404: { description: Trainee not found }
*/
router.delete('/trainees/:userId', trainerOnly, async (req, res, next) => {
try {
await archiveTrainee(prisma, req.user!.id, req.params.userId);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'coaching.archived',
entityType: 'coaching',
details: { traineeId: req.params.userId },
});
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}:
* get:
* summary: Restricted trainee detail — training metrics only (no body parameters/profile)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 404: { description: Trainee not found }
*/
router.get('/trainees/:userId', trainerOnly, async (req, res, next) => {
try {
const result = await getTraineeDetail(prisma, req.user!.id, req.params.userId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/history:
* get:
* summary: Trainee session history with plan vs. actual (trainer only)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 404: { description: Trainee not found }
*/
router.get('/trainees/:userId/history', trainerOnly, async (req, res, next) => {
try {
const result = await getTraineeHistory(prisma, req.user!.id, req.params.userId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/report:
* get:
* summary: Plan vs. actual per muscle group + recommended volume range + plan days
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 404: { description: Trainee not found }
*/
router.get('/trainees/:userId/report', trainerOnly, async (req, res, next) => {
try {
const result = await getTraineeReport(prisma, req.user!.id, req.params.userId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/moves:
* get:
* summary: Moved-day log (DayMove) for the trainee's active plan
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 404: { description: Trainee not found }
*/
router.get('/trainees/:userId/moves', trainerOnly, async (req, res, next) => {
try {
const result = await getTraineeMoves(prisma, req.user!.id, req.params.userId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/calendar:
* get:
* summary: Trainee calendar — training days of the trainee's active plan in a month
* (?month=YYYY-MM, default: current) (trainer only)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Invalid month format }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.get('/trainees/:userId/calendar', trainerOnly, async (req, res, next) => {
try {
const parsed = calendarQuerySchema.safeParse(req.query);
if (!parsed.success) throw badRequest('month must be in YYYY-MM format');
const result = await getTraineeCalendar(prisma, req.user!.id, req.params.userId, parsed.data.month);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/exercise-progress:
* get:
* summary: Per-exercise progress (1RM Epley + volume per completed session)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.get('/trainees/:userId/exercise-progress', trainerOnly, async (req, res, next) => {
try {
const result = await getTraineeExerciseProgress(prisma, req.user!.id, req.params.userId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/exercise-latest:
* get:
* summary: Most recent COMPLETED session per exercise (sets for plan prefill + 1RM)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.get('/trainees/:userId/exercise-latest', trainerOnly, async (req, res, next) => {
try {
const result = await getTraineeLatestResults(prisma, req.user!.id, req.params.userId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/plans:
* get:
* summary: The trainee's plans (with creator)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.get('/trainees/:userId/plans', trainerOnly, async (req, res, next) => {
try {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await listPlans(prisma, req.params.userId);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/plans:
* post:
* summary: Create a plan for the trainee (owner = trainee, creator = trainer)
* tags: [Trainer]
* responses:
* 201: { description: Created }
* 400: { description: Validation error / start date not a Monday / start week in the past }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
* 409: { description: Trainee already has an active plan }
*/
router.post('/trainees/:userId/plans', trainerOnly, validate(createPlanSchema), async (req, res, next) => {
try {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const data = req.body as z.infer<typeof createPlanSchema>;
const result = await createPlan(prisma, req.params.userId, data, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.created',
entityType: 'plan',
entityId: result.plan.id,
details: { title: result.plan.title, traineeId: req.params.userId },
});
res.status(201).json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:
* get:
* summary: Plan details (weeks -> days -> exercises -> sets)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.get('/trainees/:userId/plans/:planId', trainerOnly, async (req, res, next) => {
try {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await getPlan(prisma, req.params.planId, req.user!.id);
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:
* patch:
* summary: Replace plan structure (draft only)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Not a draft }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.patch(
'/trainees/:userId/plans/:planId',
trainerOnly,
validate(updatePlanSchema),
async (req, res, next) => {
try {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const data = req.body as z.infer<typeof updatePlanSchema>;
const result = await updatePlan(prisma, req.params.planId, req.user!.id, data);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.updated',
entityType: 'plan',
entityId: req.params.planId,
details: { title: data.title, traineeId: req.params.userId },
});
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}:
* delete:
* summary: Delete plan (draft only)
* tags: [Trainer]
* responses:
* 204: { description: Deleted }
* 400: { description: Not a draft }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.delete('/trainees/:userId/plans/:planId', trainerOnly, async (req, res, next) => {
try {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await deletePlan(prisma, req.params.planId, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.deleted',
entityType: 'plan',
entityId: req.params.planId,
details: { title: result.title, traineeId: req.params.userId },
});
res.status(204).end();
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}/activate:
* post:
* summary: Activate the trainee's plan (startDate must be a Monday)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Not a draft / invalid date }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
* 409: { description: Trainee already has an active plan }
*/
router.post(
'/trainees/:userId/plans/:planId/activate',
trainerOnly,
validate(activateSchema),
async (req, res, next) => {
try {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const { startDate } = req.body as z.infer<typeof activateSchema>;
const result = await activatePlan(prisma, req.params.planId, req.user!.id, startDate);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.activated',
entityType: 'plan',
entityId: req.params.planId,
details: { title: result.title, startDate, traineeId: req.params.userId },
});
res.json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}/abandon:
* post:
* summary: Abandon the trainee's plan (draft/active)
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Plan already closed }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.post('/trainees/:userId/plans/:planId/abandon', trainerOnly, async (req, res, next) => {
try {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await abandonPlan(prisma, req.params.planId, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.abandoned',
entityType: 'plan',
entityId: req.params.planId,
details: { title: result.title, traineeId: req.params.userId },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/plans/{planId}/complete:
* post:
* summary: Mark the trainee's plan as completed
* tags: [Trainer]
* responses:
* 200: { description: OK }
* 400: { description: Plan already closed }
* 403: { description: Trainer role required }
* 404: { description: Trainee or plan not found }
*/
router.post('/trainees/:userId/plans/:planId/complete', trainerOnly, async (req, res, next) => {
try {
await assertActiveTrainee(prisma, req.user!.id, req.params.userId);
const result = await completePlan(prisma, req.params.planId, req.user!.id);
await logActivity(prisma, {
actorId: req.user!.id,
action: 'plan.completed',
entityType: 'plan',
entityId: req.params.planId,
details: { title: result.title, traineeId: req.params.userId },
});
res.json(result);
} catch (e) {
next(e);
}
});
/**
* @openapi
* /trainer/trainees/{userId}/comments:
* post:
* summary: Trainer comment on the trainee (anchored to a session / exercise)
* tags: [Trainer]
* responses:
* 201: { description: Created }
* 400: { description: Invalid session anchor }
* 403: { description: Trainer role required }
* 404: { description: Trainee not found }
*/
router.post(
'/trainees/:userId/comments',
trainerOnly,
validate(commentSchema),
async (req, res, next) => {
try {
const data = req.body as z.infer<typeof commentSchema>;
const result = await addTraineeComment(prisma, req.user!.id, req.params.userId, data);
res.status(201).json(result);
} catch (e) {
next(e);
}
},
);
/**
* @openapi
* /trainer/trainees/{userId}/comments/{commentId}:
* delete:
* summary: Delete the trainer's own comment on the trainee
* tags: [Trainer]
* responses:
* 204: { description: Deleted }
* 403: { description: Trainer role required }
* 404: { description: Comment not found or not the author }
*/
router.delete('/trainees/:userId/comments/:commentId', trainerOnly, async (req, res, next) => {
try {
await deleteTraineeComment(prisma, req.user!.id, req.params.userId, req.params.commentId);
res.status(204).end();
} catch (e) {
next(e);
}
});
return router;
}

187
api/src/seed.ts Normal file
View File

@@ -0,0 +1,187 @@
import 'dotenv/config';
import bcrypt from 'bcryptjs';
import { Prisma, PrismaClient } from '@prisma/client';
import { EXERCISES, SEED_VERSION } from './data/exercises.js';
import type { EquipmentKind, EquipmentSpec } from './lib/equipmentSpec.js';
const prisma = new PrismaClient();
/**
* Default focus areas — one per muscle group present in the exercise catalog.
* The admin can rename/describe them; the muscle key is stable and links to Exercise.primaryMuscle.
* setsMin/setsMax: recommended weekly volume range in sets (decision 13 — volume warning).
*/
const FOCUS_AREAS: Array<{ name: string; muscle: string; description: string; setsMin: number; setsMax: number }> = [
{ name: 'Klatka piersiowa', muscle: 'chest', description: 'Wyciskanie, rozpiętki, pompki.', setsMin: 10, setsMax: 20 },
{ name: 'Plecy', muscle: 'back', description: 'Podciąganie, wiosłowanie, uginanie.', setsMin: 10, setsMax: 20 },
{ name: 'Nogi', muscle: 'legs', description: 'Przysiady, wykroki, prostowanie nóg.', setsMin: 10, setsMax: 18 },
{ name: 'Pośladki', muscle: 'glutes', description: 'Hip thrust, mostki, wykroki.', setsMin: 8, setsMax: 16 },
{ name: 'Barki', muscle: 'shoulders', description: 'Wyciskanie nad głowę, unoszenia.', setsMin: 8, setsMax: 16 },
{ name: 'Biceps', muscle: 'biceps', description: 'Uginanie, podciąganie.', setsMin: 6, setsMax: 12 },
{ name: 'Triceps', muscle: 'triceps', description: 'Osiadanie, wyciskanie francuskie.', setsMin: 6, setsMax: 12 },
{ name: 'Brzuch / core', muscle: 'core', description: 'Plank, unoszenia nóg, stabilizacja.', setsMin: 8, setsMax: 16 },
];
/**
* Equipment (machine/device) catalog — slug → Polish display name.
* The slug is the stable key used by the exercise seed data; the name is what
* admins and gym owners see and pick from.
* `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
*/
const EQUIPMENT: Array<{
slug: string;
name: string;
kind: EquipmentKind;
spec: EquipmentSpec | null;
description: string;
}> = [
{ slug: 'barbell', name: 'Sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: 'Sztanga z talerzami.' },
{ slug: 'dumbbells', name: 'Hantle', kind: 'DUMBBELL', spec: { minKg: 2.5, maxKg: 25 }, description: 'Hantle wolne.' },
{ slug: 'bodyweight', name: 'Masa ciała', kind: 'BODYWEIGHT', spec: null, description: 'Ćwiczenia z masą ciała.' },
{ slug: 'cable', name: 'Wyciąg', kind: 'CABLE', spec: { minKg: 5, maxKg: 50 }, description: 'Wyciąg linowy.' },
{ slug: 'dip-bars', name: 'Drążek do dipów', kind: 'BODYWEIGHT', spec: null, description: 'Stojak do dipów.' },
{ slug: 'pull-up-bar', name: 'Drążek do podciągania', kind: 'BODYWEIGHT', spec: null, description: 'Drążek do podciągania.' },
{ slug: 'leg-press', name: 'Leg press', kind: 'MACHINE', spec: { minKg: 20, maxKg: 120 }, description: 'Maszyna do prostowania nóg.' },
{ slug: 'leg-curl', name: 'Leg curl', kind: 'MACHINE', spec: { minKg: 10, maxKg: 60 }, description: 'Maszyna do uginania nóg.' },
];
/**
* Idempotent seed of the equipment catalog — upsert by name.
*/
async function seedEquipment() {
for (const eq of EQUIPMENT) {
const spec = eq.spec === null ? Prisma.JsonNull : (eq.spec as Prisma.InputJsonValue);
await prisma.equipment.upsert({
where: { name: eq.name },
update: { description: eq.description, kind: eq.kind, spec },
create: { name: eq.name, description: eq.description, kind: eq.kind, spec },
});
}
console.log(`Seeded ${EQUIPMENT.length} equipment items`);
}
/** Resolve a list of equipment slugs to equipment ids (creating any missing). */
async function resolveEquipmentIds(slugs: string[]): Promise<string[]> {
const ids: string[] = [];
for (const slug of slugs) {
const known = EQUIPMENT.find((e) => e.slug === slug);
const name = known?.name ?? slug;
const eq = await prisma.equipment.upsert({
where: { name },
update: {},
create: { name },
});
ids.push(eq.id);
}
return ids;
}
/**
* Idempotent seed (upsert by slug + seed_version).
* Re-running updates the built-in pool.
*/
async function seedExercises() {
for (const ex of EXERCISES) {
const equipmentIds = await resolveEquipmentIds(ex.equipment);
await prisma.exercise.upsert({
where: { slug: ex.slug },
update: {
name: ex.name,
primaryMuscle: ex.primaryMuscle,
secondaryMuscles: ex.secondaryMuscles,
equipment: { set: equipmentIds.map((id) => ({ id })) },
hasReps: ex.hasReps,
hasLoad: ex.hasLoad,
hasRest: ex.hasRest,
hasSets: ex.hasSets,
hasRir: ex.hasRir,
hasDifficulty: ex.hasDifficulty,
hasCardio: ex.hasCardio,
hasTime: ex.hasTime,
hasSpeed: ex.hasSpeed,
description: ex.description,
howTo: ex.howTo,
commonMistakes: ex.commonMistakes,
difficulty: ex.difficulty,
source: 'BUILTIN',
seedVersion: SEED_VERSION,
},
create: {
slug: ex.slug,
name: ex.name,
primaryMuscle: ex.primaryMuscle,
secondaryMuscles: ex.secondaryMuscles,
equipment: { connect: equipmentIds.map((id) => ({ id })) },
hasReps: ex.hasReps,
hasLoad: ex.hasLoad,
hasRest: ex.hasRest,
hasSets: ex.hasSets,
hasRir: ex.hasRir,
hasDifficulty: ex.hasDifficulty,
hasCardio: ex.hasCardio,
hasTime: ex.hasTime,
hasSpeed: ex.hasSpeed,
description: ex.description,
howTo: ex.howTo,
commonMistakes: ex.commonMistakes,
difficulty: ex.difficulty,
source: 'BUILTIN',
seedVersion: SEED_VERSION,
},
});
}
console.log(`Seeded ${EXERCISES.length} exercises (seed_version=${SEED_VERSION})`);
}
/**
* Idempotent seed of the default focus areas — upsert by muscle key.
*/
async function seedFocusAreas() {
for (const fa of FOCUS_AREAS) {
await prisma.focusArea.upsert({
where: { muscle: fa.muscle },
update: { name: fa.name, description: fa.description, setsMin: fa.setsMin, setsMax: fa.setsMax },
create: { name: fa.name, muscle: fa.muscle, description: fa.description, setsMin: fa.setsMin, setsMax: fa.setsMax },
});
}
console.log(`Seeded ${FOCUS_AREAS.length} focus areas`);
}
/**
* First admin from env vars (FITOS_FIRST_ADMIN_EMAIL / FITOS_FIRST_ADMIN_PASSWORD).
*/
async function seedFirstAdmin() {
const email = process.env.FITOS_FIRST_ADMIN_EMAIL;
if (!email) {
console.log('FITOS_FIRST_ADMIN_EMAIL not set — skipping first admin seed');
return;
}
const password = process.env.FITOS_FIRST_ADMIN_PASSWORD || 'ChangeMe123!';
const existing = await prisma.user.findUnique({ where: { email } });
if (existing) return;
const passwordHash = await bcrypt.hash(password, 10);
await prisma.user.create({
data: { email, passwordHash, isAdmin: true, firstName: 'Admin' },
});
console.log(`Created first admin: ${email} (password from FITOS_FIRST_ADMIN_PASSWORD)`);
}
async function main() {
await seedEquipment();
await seedExercises();
await seedFocusAreas();
await seedFirstAdmin();
}
main()
.catch((e) => {
console.error('Seed failed:', e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});

568
api/src/services/admin.ts Normal file
View File

@@ -0,0 +1,568 @@
import bcrypt from 'bcryptjs';
import { Prisma, type GymRole, type PrismaClient } from '@prisma/client';
import { isPrismaNotFound, isPrismaUnique } from '../lib/prisma.js';
import { publicUser } from '../lib/publicUser.js';
import { badRequest, conflict, notFound } from '../lib/errors.js';
import { removeGymClaimFiles, removeGymPhotoFiles } from '../lib/uploads.js';
import { gymPhotoUrl, listGymClaimIds } from './gyms.js';
import { resolveMuscleConflicts, toPrismaAvailability, type Availability } from './me.js';
export interface CreateGymInput {
name: string;
location?: string | null;
availability?: Availability | null;
capacity?: number | null;
}
export interface UpdateGymInput {
name?: string;
location?: string | null;
availability?: Availability | null;
capacity?: number | null;
}
export interface CreateUserInput {
email: string;
password: string;
firstName?: string;
lastName?: string;
age?: number;
isAdmin?: boolean;
}
export interface UpdateUserInput {
email?: string;
firstName?: string | null;
lastName?: string | null;
age?: number | null;
heightCm?: number | null;
phone?: string | null;
isAdmin?: boolean;
password?: string;
availability?: Availability | null;
priorities?: string | null;
exclusions?: string | null;
developMuscles?: string[];
canDoMuscles?: string[];
difficultMuscles?: string[];
avoidMuscles?: string[];
}
export type MembershipRole = 'OWNER' | 'TRAINER' | 'MEMBER';
export async function listGyms(prisma: PrismaClient) {
const gyms = await prisma.gym.findMany({
orderBy: { name: 'asc' },
include: {
_count: { select: { memberships: true } },
equipment: {
include: { equipment: true },
orderBy: { equipment: { name: 'asc' } },
},
photos: {
orderBy: [{ order: 'asc' }, { createdAt: 'asc' }],
take: 1,
},
},
});
return {
gyms: gyms.map((g) => {
const { photos, ...rest } = g;
return { ...rest, coverPhoto: photos[0] ? gymPhotoUrl(g.id, photos[0].id) : null };
}),
};
}
export async function getGym(prisma: PrismaClient, gymId: string) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: {
equipment: { include: { equipment: true }, orderBy: { equipment: { name: 'asc' } } },
photos: { orderBy: [{ order: 'asc' }, { createdAt: 'asc' }] },
_count: { select: { memberships: true } },
},
});
if (!gym) throw Object.assign(new Error('Nie znaleziono siłowni'), { status: 404 });
return gym;
}
export async function createGym(prisma: PrismaClient, data: CreateGymInput) {
const { availability, ...rest } = data;
const gym = await prisma.gym.create({
data: { ...rest, availability: toPrismaAvailability(availability) },
});
return { gym };
}
export async function updateGym(prisma: PrismaClient, id: string, data: UpdateGymInput) {
try {
const { availability, ...rest } = data;
const gym = await prisma.gym.update({
where: { id },
data: { ...rest, availability: toPrismaAvailability(availability) },
});
return { gym };
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Gym not found');
throw e;
}
}
export async function deleteGym(prisma: PrismaClient, id: string) {
const claimIds = await listGymClaimIds(prisma, id);
try {
await prisma.gym.delete({ where: { id } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Gym not found');
throw e;
}
await removeGymClaimFiles(claimIds);
removeGymPhotoFiles(id);
}
/** Add a catalog equipment item to a gym with a quantity (admin, no owner check). */
export async function addGymEquipment(
prisma: PrismaClient,
gymId: string,
equipmentId: string,
quantity = 1,
) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { equipment: true },
});
if (!gym) throw notFound('Gym not found');
const item = await prisma.equipment.findUnique({ where: { id: equipmentId } });
if (!item) throw notFound('Equipment not found');
if (gym.equipment.some((e) => e.equipmentId === equipmentId))
throw conflict('Equipment already exists in this gym — update its quantity instead');
try {
await prisma.gymEquipment.create({ data: { gymId, equipmentId, quantity } });
} catch (e) {
if (isPrismaUnique(e))
throw conflict('Equipment already exists in this gym — update its quantity instead');
throw e;
}
const updated = await prisma.gym.findUnique({
where: { id: gymId },
include: { equipment: { include: { equipment: true } } },
});
return { gym: updated };
}
/** Change the quantity of a gym's equipment item (admin, no owner check). */
export async function updateGymEquipmentQuantity(
prisma: PrismaClient,
gymId: string,
equipmentId: string,
quantity: number,
) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { equipment: true },
});
if (!gym) throw notFound('Gym not found');
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
if (!link) throw badRequest('Equipment not found in this gym');
await prisma.gymEquipment.update({ where: { id: link.id }, data: { quantity } });
const updated = await prisma.gym.findUnique({
where: { id: gymId },
include: { equipment: { include: { equipment: true } } },
});
return { gym: updated };
}
/** Remove a catalog equipment item from a gym (admin, no owner check). */
export async function removeGymEquipment(
prisma: PrismaClient,
gymId: string,
equipmentId: string,
) {
const gym = await prisma.gym.findUnique({
where: { id: gymId },
include: { equipment: true },
});
if (!gym) throw notFound('Gym not found');
const link = gym.equipment.find((e) => e.equipmentId === equipmentId);
if (!link) throw badRequest('Equipment not found in this gym');
await prisma.gymEquipment.delete({ where: { id: link.id } });
const updated = await prisma.gym.findUnique({
where: { id: gymId },
include: { equipment: { include: { equipment: true } } },
});
return { gym: updated };
}
export async function listUsers(prisma: PrismaClient, search?: string) {
const term = search?.toLowerCase();
const users = await prisma.user.findMany({
where: term
? {
OR: [
{ email: { contains: term, mode: 'insensitive' } },
{ firstName: { contains: term, mode: 'insensitive' } },
{ lastName: { contains: term, mode: 'insensitive' } },
],
}
: undefined,
include: { memberships: { include: { gym: true } } },
orderBy: { createdAt: 'desc' },
});
return {
users: users.map((u) => ({
...publicUser(u),
memberships: u.memberships.map((m) => ({
gymId: m.gymId,
roles: m.roles,
gym: m.gym,
})),
})),
};
}
export async function createUser(prisma: PrismaClient, data: CreateUserInput) {
const existing = await prisma.user.findUnique({
where: { email: data.email.toLowerCase() },
});
if (existing) throw conflict('Email already registered');
const passwordHash = await bcrypt.hash(data.password, 10);
const user = await prisma.user.create({
data: {
email: data.email.toLowerCase(),
passwordHash,
firstName: data.firstName,
lastName: data.lastName,
age: data.age,
isAdmin: data.isAdmin ?? false,
},
});
return { user: publicUser(user) };
}
export async function updateUser(
prisma: PrismaClient,
id: string,
data: UpdateUserInput,
) {
const user = await prisma.user.findUnique({ where: { id } });
if (!user) throw notFound('User not found');
const email = data.email?.toLowerCase();
if (email && email !== user.email) {
const existing = await prisma.user.findUnique({ where: { email } });
if (existing) throw conflict('Email already registered');
}
const phone = data.phone;
if (phone && phone !== user.phone) {
const phoneOwner = await prisma.user.findUnique({ where: { phone } });
if (phoneOwner) throw conflict('Phone already registered');
}
const roleChanged = data.isAdmin !== undefined && data.isAdmin !== user.isAdmin;
const passwordHash = data.password ? await bcrypt.hash(data.password, 10) : undefined;
const muscles =
data.developMuscles !== undefined ||
data.canDoMuscles !== undefined ||
data.difficultMuscles !== undefined ||
data.avoidMuscles !== undefined
? resolveMuscleConflicts(
{
developMuscles: user.developMuscles,
canDoMuscles: user.canDoMuscles,
difficultMuscles: user.difficultMuscles,
avoidMuscles: user.avoidMuscles,
},
data,
)
: {};
const updated = await prisma.user.update({
where: { id: user.id },
data: {
email,
firstName: data.firstName,
lastName: data.lastName,
age: data.age,
heightCm: data.heightCm,
phone: data.phone,
isAdmin: data.isAdmin,
passwordHash,
availability: toPrismaAvailability(data.availability),
priorities: data.priorities,
exclusions: data.exclusions,
...muscles,
...(roleChanged ? { tokenVersion: { increment: 1 } } : {}),
},
});
return { user: publicUser(updated) };
}
export async function deleteUser(prisma: PrismaClient, id: string) {
try {
await prisma.user.delete({ where: { id } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('User not found');
throw e;
}
}
export async function addMembership(
prisma: PrismaClient,
userId: string,
gymId: string,
roles: MembershipRole[],
) {
const gym = await prisma.gym.findUnique({ where: { id: gymId } });
if (!gym) throw notFound('Gym not found');
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user) throw notFound('User not found');
const existing = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId: user.id, gymId } },
});
if (existing) throw conflict('Membership already exists');
const membership = await prisma.gymMembership.create({
data: { userId: user.id, gymId, roles },
});
return { membership };
}
export async function updateMembership(
prisma: PrismaClient,
userId: string,
gymId: string,
roles: MembershipRole[],
) {
const membership = await prisma.gymMembership.findUnique({
where: { userId_gymId: { userId, gymId } },
});
if (!membership) throw notFound('Membership not found');
const updated = await prisma.gymMembership.update({
where: { userId_gymId: { userId, gymId } },
data: { roles },
});
return { membership: updated };
}
export async function removeMembership(
prisma: PrismaClient,
userId: string,
gymId: string,
) {
try {
await prisma.gymMembership.delete({
where: { userId_gymId: { userId, gymId } },
});
} catch (e) {
if (isPrismaNotFound(e)) throw badRequest('Membership not found');
throw e;
}
}
// ---------- gym claims (admin verification) ----------
export type ClaimStatus = 'PENDING' | 'APPROVED' | 'REJECTED';
/** List gym claims (both types), PENDING first, then createdAt desc. */
export async function listGymClaims(prisma: PrismaClient, status?: ClaimStatus) {
const claims = await prisma.gymClaim.findMany({
where: status ? { status } : undefined,
include: {
gym: { select: { id: true, name: true, kind: true, isPrivate: true } },
user: { select: { id: true, firstName: true, lastName: true, email: true } },
_count: { select: { documents: true } },
},
});
claims.sort(
(a, b) =>
Number(a.status !== 'PENDING') - Number(b.status !== 'PENDING') ||
b.createdAt.getTime() - a.createdAt.getTime(),
);
return {
claims: claims.map((c) => ({
id: c.id,
gymId: c.gymId,
type: c.gymId ? ('verification' as const) : ('new' as const),
gym: c.gym
? { id: c.gym.id, name: c.gym.name, kind: c.gym.kind, isPrivate: c.gym.isPrivate }
: null,
gymName: c.gymName,
gymLocation: c.gymLocation,
description: c.description,
companyName: c.companyName,
nip: c.nip,
phone: c.phone,
email: c.email,
address: c.address,
status: c.status,
rejectReason: c.rejectReason,
createdAt: c.createdAt.toISOString(),
user: {
id: c.user.id,
firstName: c.user.firstName,
lastName: c.user.lastName,
email: c.user.email,
},
documentCount: c._count.documents,
})),
};
}
/** Full claim detail (admin): claim + gym + user + documents. */
export async function getGymClaim(prisma: PrismaClient, claimId: string) {
const claim = await prisma.gymClaim.findUnique({
where: { id: claimId },
include: {
gym: { select: { id: true, name: true, kind: true, isPrivate: true } },
user: { select: { id: true, firstName: true, lastName: true, email: true, phone: true } },
documents: {
select: {
id: true,
originalName: true,
storedName: true,
mimeType: true,
sizeBytes: true,
createdAt: true,
},
},
},
});
if (!claim) throw notFound('Claim not found');
return {
claim: {
id: claim.id,
gymId: claim.gymId,
type: claim.gymId ? ('verification' as const) : ('new' as const),
gym: claim.gym
? { id: claim.gym.id, name: claim.gym.name, kind: claim.gym.kind, isPrivate: claim.gym.isPrivate }
: null,
gymName: claim.gymName,
gymLocation: claim.gymLocation,
gymAvailability: claim.gymAvailability,
gymCapacity: claim.gymCapacity,
description: claim.description,
companyName: claim.companyName,
nip: claim.nip,
phone: claim.phone,
email: claim.email,
address: claim.address,
status: claim.status,
rejectReason: claim.rejectReason,
decidedAt: claim.decidedAt ? claim.decidedAt.toISOString() : null,
createdAt: claim.createdAt.toISOString(),
user: {
id: claim.user.id,
firstName: claim.user.firstName,
lastName: claim.user.lastName,
email: claim.user.email,
phone: claim.user.phone,
},
documents: claim.documents.map((d) => ({
id: d.id,
originalName: d.originalName,
mimeType: d.mimeType,
sizeBytes: d.sizeBytes,
createdAt: d.createdAt.toISOString(),
})),
},
};
}
/**
* Approve a PENDING claim (transaction):
* - verification: gym → REAL + public, applicant → OWNER, other owners → MEMBER,
* other pending claims for the gym → REJECTED, address overrides gym.location;
* - new real: creates a REAL gym from the claim data, applicant → OWNER,
* claim.gymId → the new gym.
*/
export async function approveGymClaim(prisma: PrismaClient, adminId: string, claimId: string) {
await prisma.$transaction(async (tx) => {
const claim = await tx.gymClaim.findUnique({ where: { id: claimId } });
if (!claim) throw notFound('Claim not found');
if (claim.status !== 'PENDING') throw conflict('Claim is not pending');
if (claim.gymId) {
const gym = await tx.gym.findUnique({ where: { id: claim.gymId } });
if (!gym) throw notFound('Gym not found');
if (gym.kind !== 'VIRTUAL') throw conflict('Only virtual gyms can be verified');
await tx.gym.update({
where: { id: gym.id },
data: {
kind: 'REAL',
isPrivate: false,
...(claim.address ? { location: claim.address } : {}),
},
});
const membership = await tx.gymMembership.findUnique({
where: { userId_gymId: { userId: claim.userId, gymId: gym.id } },
});
if (membership) {
const roles: GymRole[] = membership.roles.includes('OWNER')
? membership.roles
: ['OWNER', ...membership.roles];
await tx.gymMembership.update({ where: { id: membership.id }, data: { roles } });
} else {
await tx.gymMembership.create({
data: { userId: claim.userId, gymId: gym.id, roles: ['OWNER'] },
});
}
const otherOwners = await tx.gymMembership.findMany({
where: { gymId: gym.id, userId: { not: claim.userId }, roles: { has: 'OWNER' } },
});
for (const m of otherOwners) {
const roles = m.roles.filter((r) => r !== 'OWNER');
await tx.gymMembership.update({
where: { id: m.id },
data: { roles: roles.length > 0 ? roles : ['MEMBER'] },
});
}
await tx.gymClaim.updateMany({
where: { gymId: gym.id, status: 'PENDING', id: { not: claim.id } },
data: {
status: 'REJECTED',
rejectReason: 'Zatwierdzono inny wniosek',
decidedById: adminId,
decidedAt: new Date(),
},
});
} else {
const gym = await tx.gym.create({
data: {
name: claim.gymName!,
location: claim.gymLocation!,
availability:
claim.gymAvailability === null ? Prisma.DbNull : claim.gymAvailability,
capacity: claim.gymCapacity,
kind: 'REAL',
isPrivate: false,
},
});
await tx.gymMembership.create({
data: { userId: claim.userId, gymId: gym.id, roles: ['OWNER'] },
});
await tx.gymClaim.update({ where: { id: claim.id }, data: { gymId: gym.id } });
}
await tx.gymClaim.update({
where: { id: claim.id },
data: { status: 'APPROVED', decidedById: adminId, decidedAt: new Date() },
});
});
}
/** Reject a PENDING claim with an optional reason. */
export async function rejectGymClaim(
prisma: PrismaClient,
adminId: string,
claimId: string,
reason?: string,
) {
const claim = await prisma.gymClaim.findUnique({ where: { id: claimId } });
if (!claim) throw notFound('Claim not found');
if (claim.status !== 'PENDING') throw conflict('Claim is not pending');
await prisma.gymClaim.update({
where: { id: claimId },
data: {
status: 'REJECTED',
rejectReason: reason?.trim() ? reason.trim() : null,
decidedById: adminId,
decidedAt: new Date(),
},
});
}

86
api/src/services/audit.ts Normal file
View File

@@ -0,0 +1,86 @@
import type { Prisma, PrismaClient } from '@prisma/client';
import { logger } from '../lib/logger.js';
export interface ActivityLogInput {
actorId: string;
action: string;
entityType: string;
entityId?: string | null;
details?: Record<string, unknown> | null;
}
/**
* Best-effort audit write — a failure must never break the main request.
* Errors are reported to the app logger only.
* `details` always includes the actor's ID (merged under `actorId`).
*/
export async function logActivity(prisma: PrismaClient, input: ActivityLogInput) {
try {
await prisma.activityLog.create({
data: {
actorId: input.actorId,
action: input.action,
entityType: input.entityType,
entityId: input.entityId ?? null,
details: { actorId: input.actorId, ...(input.details ?? {}) } as Prisma.InputJsonValue,
},
});
} catch (e) {
logger.error({ err: e, action: input.action, actorId: input.actorId }, 'Failed to write activity log');
}
}
export interface ActivityLogFilters {
action?: string;
userId?: string;
/** Inclusive ISO date (YYYY-MM-DD). */
from?: string;
/** Inclusive ISO date (YYYY-MM-DD). */
to?: string;
limit: number;
offset: number;
}
export interface ActivityLogActor {
id: string;
email: string;
firstName: string | null;
lastName: string | null;
}
export interface ActivityLogEntry {
id: string;
action: string;
entityType: string;
entityId: string | null;
details: Record<string, unknown> | null;
createdAt: Date;
actor: ActivityLogActor;
}
export async function listActivityLogs(prisma: PrismaClient, filters: ActivityLogFilters) {
const where: Prisma.ActivityLogWhereInput = {
...(filters.action ? { action: filters.action } : {}),
...(filters.userId ? { actorId: filters.userId } : {}),
createdAt:
filters.from || filters.to
? {
...(filters.from ? { gte: new Date(`${filters.from}T00:00:00.000Z`) } : {}),
...(filters.to ? { lte: new Date(`${filters.to}T23:59:59.999Z`) } : {}),
}
: undefined,
};
const [logs, total] = await Promise.all([
prisma.activityLog.findMany({
where,
include: {
actor: { select: { id: true, email: true, firstName: true, lastName: true } },
},
orderBy: { createdAt: 'desc' },
take: filters.limit,
skip: filters.offset,
}),
prisma.activityLog.count({ where }),
]);
return { logs, total };
}

63
api/src/services/auth.ts Normal file
View File

@@ -0,0 +1,63 @@
import bcrypt from 'bcryptjs';
import type { PrismaClient } from '@prisma/client';
import { signAccessToken, signRefreshToken, verifyRefreshToken } from '../lib/jwt.js';
import { publicUser } from '../lib/publicUser.js';
import { conflict, unauthorized } from '../lib/errors.js';
export interface RegisterInput {
email: string;
password: string;
firstName?: string;
lastName?: string;
}
export interface LoginInput {
email: string;
password: string;
}
export interface AuthResult {
user: ReturnType<typeof publicUser>;
accessToken: string;
refreshToken: string;
}
export async function register(
prisma: PrismaClient,
input: RegisterInput,
): Promise<AuthResult> {
const email = input.email.toLowerCase();
const existing = await prisma.user.findUnique({ where: { email } });
if (existing) throw conflict('Email already registered');
const passwordHash = await bcrypt.hash(input.password, 10);
const user = await prisma.user.create({
data: { email, passwordHash, firstName: input.firstName, lastName: input.lastName },
});
return {
user: publicUser(user),
accessToken: signAccessToken(user.id, user.tokenVersion),
refreshToken: signRefreshToken(user.id, user.tokenVersion),
};
}
export async function login(prisma: PrismaClient, input: LoginInput): Promise<AuthResult> {
const user = await prisma.user.findUnique({ where: { email: input.email.toLowerCase() } });
if (!user) throw unauthorized('Invalid credentials');
const ok = await bcrypt.compare(input.password, user.passwordHash);
if (!ok) throw unauthorized('Invalid credentials');
return {
user: publicUser(user),
accessToken: signAccessToken(user.id, user.tokenVersion),
refreshToken: signRefreshToken(user.id, user.tokenVersion),
};
}
export async function refresh(
prisma: PrismaClient,
token: string,
): Promise<{ accessToken: string }> {
const payload = verifyRefreshToken(token);
const user = await prisma.user.findUnique({ where: { id: payload.sub } });
if (!user || user.tokenVersion !== payload.tv) throw unauthorized('Token revoked');
return { accessToken: signAccessToken(user.id, user.tokenVersion) };
}

View File

@@ -0,0 +1,46 @@
import type { PrismaClient } from '@prisma/client';
export async function getCalendar(
prisma: PrismaClient,
userId: string,
month?: string,
) {
const now = new Date();
let year: number;
let mon: number;
if (month) {
[year, mon] = month.split('-').map(Number);
} else {
year = now.getFullYear();
mon = now.getMonth() + 1;
}
const start = new Date(year, mon - 1, 1);
const end = new Date(year, mon, 1);
const days = await prisma.planDay.findMany({
where: {
week: { plan: { userId, status: 'ACTIVE' } },
date: { gte: start, lt: end },
},
include: {
exercises: {
include: { exercise: { select: { name: true, primaryMuscle: true } } },
},
},
orderBy: { date: 'asc' },
});
return {
month: `${year}-${String(mon).padStart(2, '0')}`,
days: days.map((d) => ({
id: d.id,
date: d.date!.toISOString(),
status: d.status,
dayOfWeek: d.dayOfWeek,
exercises: d.exercises.map((e) => ({
name: e.exercise.name,
muscle: e.exercise.primaryMuscle,
})),
})),
};
}

View File

@@ -0,0 +1,90 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, notFound } from '../lib/errors.js';
import { assertActiveTrainee } from './trainer.js';
export interface CommentInput {
body: string;
sessionId?: string;
sessionExerciseId?: string;
}
/**
* The anchor must be a COMPLETED session of the owner; the exercise (when
* given) must belong to that session and not be removed.
*/
async function assertSessionAnchor(prisma: PrismaClient, ownerId: string, input: CommentInput) {
if (!input.sessionId) throw badRequest('sessionId is required');
const session = await prisma.trainingSession.findUnique({
where: { id: input.sessionId },
include: { day: { select: { week: { select: { plan: { select: { userId: true } } } } } } },
});
// A session of another user is indistinguishable from a missing one.
if (!session || session.day.week.plan.userId !== ownerId) throw notFound('Session not found');
if (session.status !== 'COMPLETED') throw badRequest('Session is not completed');
if (input.sessionExerciseId) {
const se = await prisma.sessionExercise.findFirst({
where: { id: input.sessionExerciseId, sessionId: session.id },
});
if (!se || se.removed) throw badRequest('Exercise does not belong to this session');
}
}
/** Trainer comment on the trainee (target = trainee, author = trainer). */
export async function addTraineeComment(
prisma: PrismaClient,
trainerId: string,
traineeId: string,
input: CommentInput,
) {
await assertActiveTrainee(prisma, trainerId, traineeId);
await assertSessionAnchor(prisma, traineeId, input);
const comment = await prisma.comment.create({
data: {
authorId: trainerId,
targetUserId: traineeId,
sessionId: input.sessionId ?? null,
sessionExerciseId: input.sessionExerciseId ?? null,
body: input.body,
},
});
return { comment };
}
/** Delete a trainer comment on the trainee (author = trainer only). */
export async function deleteTraineeComment(
prisma: PrismaClient,
trainerId: string,
traineeId: string,
commentId: string,
) {
await assertActiveTrainee(prisma, trainerId, traineeId);
const comment = await prisma.comment.findFirst({
where: { id: commentId, targetUserId: traineeId, authorId: trainerId },
});
if (!comment) throw notFound('Comment not found');
await prisma.comment.delete({ where: { id: comment.id } });
}
/** User comment on their own session (target = author = the user). */
export async function addMyComment(prisma: PrismaClient, userId: string, input: CommentInput) {
await assertSessionAnchor(prisma, userId, input);
const comment = await prisma.comment.create({
data: {
authorId: userId,
targetUserId: userId,
sessionId: input.sessionId ?? null,
sessionExerciseId: input.sessionExerciseId ?? null,
body: input.body,
},
});
return { comment };
}
/** Delete a comment the user made on themselves. */
export async function deleteMyComment(prisma: PrismaClient, userId: string, commentId: string) {
const comment = await prisma.comment.findFirst({
where: { id: commentId, targetUserId: userId, authorId: userId },
});
if (!comment) throw notFound('Comment not found');
await prisma.comment.delete({ where: { id: comment.id } });
}

View File

@@ -0,0 +1,104 @@
import type { PrismaClient } from '@prisma/client';
import { getKillstreak } from './killstreak.js';
export async function getDashboard(prisma: PrismaClient, userId: string) {
const activePlan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
});
const killstreak = activePlan ? await getKillstreak(prisma, userId) : 0;
let nextTraining: {
dayId: string;
date: string;
exercises: { name: string; muscle: string }[];
} | null = null;
let progress: { completed: number; total: number; percent: number } | null = null;
let extra: { sets: number } | null = null;
let missing: { sets: number } | null = null;
if (activePlan) {
const days = await prisma.planDay.findMany({
where: { week: { planId: activePlan.id } },
include: { exercises: { include: { exercise: { select: { name: true, primaryMuscle: true } } } } },
});
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const upcoming = days
.filter((d) => d.status === 'PLANNED' && d.date && d.date >= startOfToday)
.sort((a, b) => a.date!.getTime() - b.date!.getTime())[0];
if (upcoming) {
nextTraining = {
dayId: upcoming.id,
date: upcoming.date!.toISOString(),
exercises: upcoming.exercises.map((e) => ({
name: e.exercise.name,
muscle: e.exercise.primaryMuscle,
})),
};
}
const total = days.length;
const done = days.filter(
(d) => d.status === 'COMPLETED' || d.status === 'SKIPPED',
).length;
progress = {
completed: done,
total,
percent: total > 0 ? Math.round((done / total) * 100) : 0,
};
// Extra = sets performed beyond the plan (planSetId = null) in completed sessions:
// sets of exercises added beyond the plan + additional sets of planned exercises.
const extraSets = await prisma.sessionSet.count({
where: {
reps: { not: null },
planSetId: null,
exercise: {
removed: false,
hidden: false,
session: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } },
},
},
});
extra = { sets: extraSets };
// Missing = planned sets left undone in completed sessions
// (planned set count minus planned sets with recorded reps).
const completedSessions = await prisma.trainingSession.findMany({
where: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } },
include: {
exercises: {
where: { removed: false, hidden: false },
include: {
planExercise: { include: { sets: true } },
sets: { select: { planSetId: true, reps: true } },
},
},
},
});
let plannedSetCount = 0;
let donePlannedSetCount = 0;
for (const s of completedSessions) {
for (const ex of s.exercises) {
if (ex.planExercise) plannedSetCount += ex.planExercise.sets.length;
for (const st of ex.sets) {
if (st.planSetId != null && st.reps != null) donePlannedSetCount++;
}
}
}
missing = { sets: plannedSetCount - donePlannedSetCount };
}
return {
killstreak,
nextTraining,
progress,
extra,
missing,
activePlan: activePlan
? { id: activePlan.id, title: activePlan.title, startDate: activePlan.startDate }
: null,
};
}

View File

@@ -0,0 +1,87 @@
import { Prisma, type PrismaClient } from '@prisma/client';
import { isPrismaNotFound, isPrismaUnique } from '../lib/prisma.js';
import { badRequest, conflict, notFound } from '../lib/errors.js';
import { validateEquipmentSpec, type EquipmentKind, type EquipmentSpec } from '../lib/equipmentSpec.js';
/** `spec` is validated against `kind` inside the service (unknown at the boundary). */
export interface EquipmentInput {
name: string;
description?: string | null;
kind: EquipmentKind;
spec?: unknown;
}
export interface EquipmentUpdateInput {
name?: string;
description?: string | null;
kind?: EquipmentKind;
spec?: unknown;
}
/** Convert a spec payload to a Prisma JSON value (null → JsonNull). */
function toPrismaSpec(spec: EquipmentSpec) {
return spec === null ? Prisma.JsonNull : (spec as Prisma.InputJsonValue);
}
/** List the equipment (machine/device) catalog. */
export async function listEquipment(prisma: PrismaClient) {
const equipment = await prisma.equipment.findMany({ orderBy: { name: 'asc' } });
return { equipment };
}
/** Create an equipment catalog entry (kind determines the spec shape). */
export async function createEquipment(prisma: PrismaClient, data: EquipmentInput) {
const checked = validateEquipmentSpec(data.kind, data.spec);
if (!checked.ok) throw badRequest(checked.error);
try {
const item = await prisma.equipment.create({
data: {
name: data.name,
description: data.description ?? null,
kind: data.kind,
spec: toPrismaSpec(checked.spec),
},
});
return { equipment: item };
} catch (e) {
if (isPrismaUnique(e)) throw conflict('Equipment with this name already exists');
throw e;
}
}
/**
* Update an equipment catalog entry.
* `spec` is validated against the resulting `kind` (existing value kept when not provided).
*/
export async function updateEquipment(
prisma: PrismaClient,
id: string,
data: EquipmentUpdateInput,
) {
const existing = await prisma.equipment.findUnique({ where: { id } });
if (!existing) throw notFound('Equipment not found');
const kind = data.kind ?? existing.kind;
const spec = data.spec !== undefined ? data.spec : existing.spec;
const checked = validateEquipmentSpec(kind, spec);
if (!checked.ok) throw badRequest(checked.error);
const item = await prisma.equipment.update({
where: { id },
data: {
name: data.name,
description: data.description,
kind,
spec: toPrismaSpec(checked.spec),
},
});
return { equipment: item };
}
/** Delete an equipment catalog entry (unlinking it from exercises and gyms). */
export async function deleteEquipment(prisma: PrismaClient, id: string) {
try {
await prisma.equipment.delete({ where: { id } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Equipment not found');
throw e;
}
}

View File

@@ -0,0 +1,15 @@
import type { PrismaClient } from '@prisma/client';
import { notFound } from '../lib/errors.js';
const include = { equipment: { orderBy: { name: 'asc' as const } } };
export async function listExercisePool(prisma: PrismaClient) {
const exercises = await prisma.exercise.findMany({ include, orderBy: { name: 'asc' } });
return { exercises };
}
export async function getExercisePool(prisma: PrismaClient, id: string) {
const exercise = await prisma.exercise.findUnique({ where: { id }, include });
if (!exercise) throw notFound('Exercise not found');
return { exercise };
}

View File

@@ -0,0 +1,212 @@
import type { PrismaClient } from '@prisma/client';
import { assertActiveTrainee } from './trainer.js';
export interface ExerciseProgressPoint {
date: string;
oneRm: number | null;
volumeKg: number | null;
reps: number;
sets: number;
}
export interface ExerciseProgress {
exerciseId: string;
name: string;
muscle: string;
/** Ascending, one point per COMPLETED session. */
points: ExerciseProgressPoint[];
}
export interface RawSet {
reps: number | null;
loadKg: number | null;
}
export interface RawExercise {
exerciseId: string;
name: string;
muscle: string;
sets: RawSet[];
}
export interface RawSession {
date: string;
exercises: RawExercise[];
}
/**
* Pure aggregation (unit-testable): one point per session per exercise.
* - oneRm = max(loadKg × (1 + reps/30)) across sets with both values (Epley);
* - volumeKg = Σ(loadKg × reps) across sets with both values;
* - reps = Σ reps; sets = count of sets with reps.
*/
export function aggregateExerciseProgress(sessions: RawSession[]): ExerciseProgress[] {
const byExercise = new Map<string, { name: string; muscle: string; points: ExerciseProgressPoint[] }>();
for (const s of sessions) {
for (const ex of s.exercises) {
let oneRm: number | null = null;
let volumeKg: number | null = null;
let reps = 0;
let sets = 0;
for (const st of ex.sets) {
if (st.reps == null) continue;
reps += st.reps;
sets += 1;
if (st.loadKg != null) {
const epley = st.loadKg * (1 + st.reps / 30);
if (oneRm == null || epley > oneRm) oneRm = epley;
volumeKg = (volumeKg ?? 0) + st.loadKg * st.reps;
}
}
const entry = byExercise.get(ex.exerciseId) ?? { name: ex.name, muscle: ex.muscle, points: [] };
entry.points.push({
date: s.date,
oneRm: oneRm == null ? null : Math.round(oneRm * 10) / 10,
volumeKg: volumeKg == null ? null : Math.round(volumeKg),
reps,
sets,
});
byExercise.set(ex.exerciseId, entry);
}
}
return [...byExercise.entries()]
.filter(([, v]) => v.points.length > 0)
.map(([exerciseId, v]) => ({
exerciseId,
name: v.name,
muscle: v.muscle,
points: [...v.points].sort((a, b) => a.date.localeCompare(b.date)),
}));
}
export interface LatestExerciseSet {
reps: number | null;
loadKg: number | null;
}
export interface LatestExerciseResult {
exerciseId: string;
name: string;
muscle: string;
/** ISO date of the most recent COMPLETED session that included the exercise. */
date: string;
/** Sets of that session (reps/loadKg, null when unrecorded) — for plan prefill. */
sets: LatestExerciseSet[];
/** Epley 1RM max across the session's sets (null when no set has both values). */
oneRm: number | null;
}
/**
* Pure aggregation (unit-testable): for each exercise, the most recent session
* (by date). oneRm = max(loadKg × (1 + reps/30)) across sets with both values;
* sets are returned raw (reps/loadKg, null when unrecorded) for plan prefill.
*/
export function latestExerciseResults(sessions: RawSession[]): LatestExerciseResult[] {
const latest = new Map<string, { name: string; muscle: string; date: string; sets: RawSet[] }>();
for (const s of sessions) {
for (const ex of s.exercises) {
const existing = latest.get(ex.exerciseId);
if (!existing || s.date > existing.date) {
latest.set(ex.exerciseId, { name: ex.name, muscle: ex.muscle, date: s.date, sets: ex.sets });
}
}
}
return [...latest.entries()].map(([exerciseId, v]) => {
let oneRm: number | null = null;
for (const st of v.sets) {
if (st.reps == null || st.loadKg == null) continue;
const epley = st.loadKg * (1 + st.reps / 30);
if (oneRm == null || epley > oneRm) oneRm = epley;
}
return {
exerciseId,
name: v.name,
muscle: v.muscle,
date: v.date,
sets: v.sets.map((st) => ({ reps: st.reps, loadKg: st.loadKg })),
oneRm: oneRm == null ? null : Math.round(oneRm * 10) / 10,
};
});
}
/**
* Per-exercise progress for the user: all COMPLETED sessions (no 30-session
* limit), exercises and sets not removed/hidden.
*/
export async function getExerciseProgress(prisma: PrismaClient, userId: string) {
const sessions = await prisma.trainingSession.findMany({
where: { status: 'COMPLETED', day: { week: { plan: { userId } } } },
orderBy: { startedAt: 'asc' },
include: {
exercises: {
where: { removed: false, hidden: false },
orderBy: { order: 'asc' },
include: {
exercise: { select: { id: true, name: true, primaryMuscle: true } },
sets: {
where: { removed: false },
orderBy: { index: 'asc' },
include: { planSet: { select: { loadKg: true } } },
},
},
},
},
});
const raw: RawSession[] = sessions.map((s) => ({
date: s.startedAt.toISOString(),
exercises: s.exercises.map((e) => ({
exerciseId: e.exercise.id,
name: e.exercise.name,
muscle: e.exercise.primaryMuscle,
sets: e.sets.map((st) => ({ reps: st.reps, loadKg: st.planSet?.loadKg ?? null })),
})),
}));
return { exercises: aggregateExerciseProgress(raw) };
}
/** Per-exercise progress for the trainee (trainer must have an ACTIVE relation). */
export async function getTraineeExerciseProgress(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
return getExerciseProgress(prisma, userId);
}
/**
* Most recent COMPLETED session per exercise (exercises/sets not removed/hidden),
* with the raw sets for plan prefill. Same query shape as getExerciseProgress.
*/
export async function getLatestExerciseResults(prisma: PrismaClient, userId: string) {
const sessions = await prisma.trainingSession.findMany({
where: { status: 'COMPLETED', day: { week: { plan: { userId } } } },
orderBy: { startedAt: 'asc' },
include: {
exercises: {
where: { removed: false, hidden: false },
orderBy: { order: 'asc' },
include: {
exercise: { select: { id: true, name: true, primaryMuscle: true } },
sets: {
where: { removed: false },
orderBy: { index: 'asc' },
include: { planSet: { select: { loadKg: true } } },
},
},
},
},
});
const raw: RawSession[] = sessions.map((s) => ({
date: s.startedAt.toISOString(),
exercises: s.exercises.map((e) => ({
exerciseId: e.exercise.id,
name: e.exercise.name,
muscle: e.exercise.primaryMuscle,
sets: e.sets.map((st) => ({ reps: st.reps, loadKg: st.planSet?.loadKg ?? null })),
})),
}));
return { results: latestExerciseResults(raw) };
}
/** Latest results for the trainee (trainer must have an ACTIVE relation). */
export async function getTraineeLatestResults(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
return getLatestExerciseResults(prisma, userId);
}

View File

@@ -0,0 +1,123 @@
import type { Prisma, PrismaClient } from '@prisma/client';
import { isPrismaNotFound, isPrismaUnique } from '../lib/prisma.js';
import { conflict, notFound } from '../lib/errors.js';
export interface ExerciseInput {
name: string;
primaryMuscle: string;
secondaryMuscles?: string[];
description?: string | null;
howTo?: string | null;
commonMistakes?: string | null;
difficulty?: number;
/** Equipment ids to link (replaces the current set when provided). */
equipmentIds?: string[];
}
const exerciseInclude = {
equipment: { orderBy: { name: 'asc' } },
} satisfies Prisma.ExerciseInclude;
/** List all exercise types with their linked equipment. */
export async function listExercises(prisma: PrismaClient) {
const exercises = await prisma.exercise.findMany({
include: exerciseInclude,
orderBy: { name: 'asc' },
});
return { exercises };
}
/** Get a single exercise type with its linked equipment. */
export async function getExercise(prisma: PrismaClient, id: string) {
const exercise = await prisma.exercise.findUnique({
where: { id },
include: exerciseInclude,
});
if (!exercise) throw notFound('Exercise not found');
return { exercise };
}
/** Generate a unique slug from a name (lowercase, hyphenated, with a short suffix). */
async function uniqueSlug(prisma: PrismaClient, name: string): Promise<string> {
const base =
name
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/(^-|-$)/g, '') || 'exercise';
let slug = base;
for (let i = 0; i < 10; i++) {
const existing = await prisma.exercise.findUnique({ where: { slug } });
if (!existing) return slug;
slug = `${base}-${Math.random().toString(36).slice(2, 7)}`;
}
throw conflict('Could not generate a unique slug');
}
/** Create a new exercise type (global catalog, source=BUILTIN). */
export async function createExercise(prisma: PrismaClient, data: ExerciseInput) {
const slug = await uniqueSlug(prisma, data.name);
const equipment = data.equipmentIds
? { connect: data.equipmentIds.map((id) => ({ id })) }
: undefined;
const exercise = await prisma.exercise.create({
data: {
slug,
name: data.name,
primaryMuscle: data.primaryMuscle,
secondaryMuscles: data.secondaryMuscles ?? [],
description: data.description ?? null,
howTo: data.howTo ?? null,
commonMistakes: data.commonMistakes ?? null,
difficulty: data.difficulty ?? 3,
source: 'BUILTIN',
equipment,
},
include: exerciseInclude,
});
return { exercise };
}
/**
* Update an exercise type. Equipment is replaced wholesale when `equipmentIds`
* is provided; other fields are updated only when present.
*/
export async function updateExercise(
prisma: PrismaClient,
id: string,
data: Partial<ExerciseInput>,
) {
const existing = await prisma.exercise.findUnique({ where: { id } });
if (!existing) throw notFound('Exercise not found');
const exercise = await prisma.exercise.update({
where: { id },
data: {
name: data.name,
primaryMuscle: data.primaryMuscle,
secondaryMuscles: data.secondaryMuscles,
description: data.description,
howTo: data.howTo,
commonMistakes: data.commonMistakes,
difficulty: data.difficulty,
...(data.equipmentIds !== undefined
? { equipment: { set: data.equipmentIds.map((eid) => ({ id: eid })) } }
: {}),
},
include: exerciseInclude,
});
return { exercise };
}
/** Delete an exercise type. Fails if it is referenced by plans/sessions. */
export async function deleteExercise(prisma: PrismaClient, id: string) {
const refs = await prisma.planExercise.count({ where: { exerciseId: id } });
if (refs > 0) throw conflict('Exercise is used in plans and cannot be deleted');
try {
await prisma.exercise.delete({ where: { id } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Exercise not found');
if (isPrismaUnique(e)) throw conflict('Exercise is referenced and cannot be deleted');
throw e;
}
}

View File

@@ -0,0 +1,61 @@
import type { PrismaClient } from '@prisma/client';
import { isPrismaNotFound } from '../lib/prisma.js';
import { conflict, notFound } from '../lib/errors.js';
export interface FocusAreaInput {
name: string;
muscle: string;
description?: string | null;
setsMin?: number | null;
setsMax?: number | null;
}
export async function listFocusAreas(prisma: PrismaClient) {
const focusAreas = await prisma.focusArea.findMany({ orderBy: { name: 'asc' } });
return { focusAreas };
}
export async function createFocusArea(prisma: PrismaClient, data: FocusAreaInput) {
const existing = await prisma.focusArea.findUnique({ where: { muscle: data.muscle } });
if (existing) throw conflict('Focus area with this muscle already exists');
const focusArea = await prisma.focusArea.create({
data: {
name: data.name,
muscle: data.muscle,
description: data.description ?? null,
setsMin: data.setsMin ?? null,
setsMax: data.setsMax ?? null,
},
});
return { focusArea };
}
export async function updateFocusArea(
prisma: PrismaClient,
id: string,
data: Partial<FocusAreaInput>,
) {
const existing = await prisma.focusArea.findUnique({ where: { id } });
if (!existing) throw notFound('Focus area not found');
const focusArea = await prisma.focusArea.update({
where: { id },
data: {
name: data.name,
muscle: data.muscle,
description: data.description,
// undefined fields are skipped by Prisma — partial updates keep existing values
setsMin: data.setsMin,
setsMax: data.setsMax,
},
});
return { focusArea };
}
export async function deleteFocusArea(prisma: PrismaClient, id: string) {
try {
await prisma.focusArea.delete({ where: { id } });
} catch (e) {
if (isPrismaNotFound(e)) throw notFound('Focus area not found');
throw e;
}
}

View File

@@ -0,0 +1,73 @@
import type { PrismaClient } from '@prisma/client';
import { notFound } from '../lib/errors.js';
interface PlanExerciseRef {
id: string;
name: string;
primaryMuscle: string;
secondaryMuscles: string[];
}
/**
* Causal chain: links the user's selected focus muscles (develop / canDo /
* difficult / avoid) to the exercises in their active plan that target them.
* Lets the trainer see what the person works on, what is hard, and what to avoid.
*/
export async function getFocusChain(prisma: PrismaClient, userId: string) {
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user) throw notFound('User not found');
const activePlan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
include: {
weeks: {
include: {
days: {
include: {
exercises: { include: { exercise: true } },
},
},
},
},
},
});
// Unique exercises in the active plan (dedup by exercise id)
const uniqueExercises = new Map<string, PlanExerciseRef>();
if (activePlan) {
for (const week of activePlan.weeks) {
for (const day of week.days) {
for (const ex of day.exercises) {
if (!uniqueExercises.has(ex.exerciseId)) {
uniqueExercises.set(ex.exerciseId, {
id: ex.exercise.id,
name: ex.exercise.name,
primaryMuscle: ex.exercise.primaryMuscle,
secondaryMuscles: ex.exercise.secondaryMuscles,
});
}
}
}
}
}
const exercises = [...uniqueExercises.values()];
const focusAreas = await prisma.focusArea.findMany();
const focusAreaMap = new Map(focusAreas.map((fa) => [fa.muscle, fa]));
const buildChain = (muscles: string[]) =>
muscles.map((muscle) => ({
muscle,
name: focusAreaMap.get(muscle)?.name ?? muscle,
exercises: exercises.filter(
(p) => p.primaryMuscle === muscle || p.secondaryMuscles.includes(muscle),
),
}));
return {
develop: buildChain(user.developMuscles),
canDo: buildChain(user.canDoMuscles),
difficult: buildChain(user.difficultMuscles),
avoid: buildChain(user.avoidMuscles),
};
}

1033
api/src/services/gyms.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,80 @@
import type { PrismaClient } from '@prisma/client';
export interface EffectiveSession {
exercises: {
hidden: boolean;
removed: boolean;
planExercise: { sets: { id: string }[] } | null;
sets: { planSetId: string | null; reps: number | null }[];
}[];
}
/**
* A training is "effective" (counts toward killstreak) when the user performed
* all sets of the session: planned sets + sets of added exercises.
*/
export function isSessionEffective(session: EffectiveSession): boolean {
for (const ex of session.exercises) {
if (ex.hidden || ex.removed) continue;
if (ex.planExercise) {
for (const ps of ex.planExercise.sets) {
const done = ex.sets.some((s) => s.planSetId === ps.id && s.reps != null);
if (!done) return false;
}
} else {
if (ex.sets.length === 0) return false;
for (const s of ex.sets) {
if (s.reps == null) return false;
}
}
}
return true;
}
/**
* Killstreak = number of consecutive effective trainings (regardless of day).
* Grows by 1 for each effective training; resets to 0 after a skip
* (including auto-expired days) or a partially completed day.
*/
export async function getKillstreak(prisma: PrismaClient, userId: string): Promise<number> {
const days = await prisma.planDay.findMany({
where: {
week: { plan: { userId, status: 'ACTIVE' } },
date: { not: null },
},
orderBy: { date: 'asc' },
include: {
sessions: {
where: { status: 'COMPLETED' },
include: {
exercises: {
include: {
sets: { select: { planSetId: true, reps: true } },
planExercise: { include: { sets: { select: { id: true } } } },
},
},
},
},
},
});
const now = new Date();
const startOfTomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
let streak = 0;
for (const day of days) {
if (day.date! >= startOfTomorrow) break; // future day — not yet relevant
if (day.status === 'COMPLETED') {
const session = day.sessions[0];
if (session && isSessionEffective(session)) {
streak++; // effective training
} else {
streak = 0; // partially completed day resets the streak
}
} else if (day.status === 'SKIPPED') {
streak = 0; // skipped (manual or auto-expired) resets the streak
}
// PLANNED days (today, not yet done) do not change the streak
}
return streak;
}

314
api/src/services/me.ts Normal file
View File

@@ -0,0 +1,314 @@
import { Prisma } from '@prisma/client';
import type { PrismaClient } from '@prisma/client';
import { publicUser } from '../lib/publicUser.js';
import { conflict, notFound } from '../lib/errors.js';
export interface DayAvailability {
start: string;
end: string;
}
export type Availability = Array<DayAvailability | null>;
/**
* Prisma JSON columns reject a literal `null`. Map null -> Prisma.DbNull
* (clears the column) and undefined -> undefined (leave unchanged).
*/
export function toPrismaJson(value: unknown) {
if (value === undefined) return undefined;
if (value === null) return Prisma.DbNull;
return value as Prisma.InputJsonValue;
}
export function toPrismaAvailability(value: Availability | null | undefined) {
return toPrismaJson(value);
}
export interface SocialMediaEntry {
platform: 'INSTAGRAM' | 'TIKTOK' | 'YOUTUBE' | 'FACEBOOK' | 'X' | 'OTHER';
url: string;
label?: string;
}
export interface UpdateProfileInput {
firstName?: string | null;
lastName?: string | null;
nickname?: string | null;
socialMedia?: SocialMediaEntry[] | null;
age?: number | null;
heightCm?: number | null;
phone?: string | null;
availability?: Availability | null;
priorities?: string | null;
exclusions?: string | null;
developMuscles?: string[];
canDoMuscles?: string[];
difficultMuscles?: string[];
avoidMuscles?: string[];
}
export interface WeightInput {
value: number;
date?: string;
}
export interface CircumferenceInput {
name: string;
value: number;
date?: string;
}
export async function getProfile(prisma: PrismaClient, userId: string) {
const user = await prisma.user.findUnique({
where: { id: userId },
include: {
memberships: {
include: {
gym: {
include: {
equipment: {
include: { equipment: true },
orderBy: { equipment: { name: 'asc' as const } },
},
},
},
},
orderBy: { gym: { name: 'asc' } },
},
},
});
if (!user) throw notFound('User not found');
return {
user: publicUser(user),
memberships: user.memberships.map((m) => ({
gymId: m.gymId,
roles: m.roles,
gym: m.gym,
})),
};
}
export interface MuscleGroups {
developMuscles: string[];
canDoMuscles: string[];
difficultMuscles: string[];
avoidMuscles: string[];
}
/**
* A muscle cannot be both developed and avoided, nor both "can do" and "difficult".
* When the request (or the resulting state) would create an overlap, the
* conservative side wins: avoid over develop, difficult over canDo.
*/
export function resolveMuscleConflicts(
current: MuscleGroups,
data: Partial<MuscleGroups>,
): MuscleGroups {
const develop = new Set(data.developMuscles ?? current.developMuscles);
const canDo = new Set(data.canDoMuscles ?? current.canDoMuscles);
const difficult = new Set(data.difficultMuscles ?? current.difficultMuscles);
const avoid = new Set(data.avoidMuscles ?? current.avoidMuscles);
for (const m of avoid) {
if (develop.has(m)) develop.delete(m);
}
for (const m of difficult) {
if (canDo.has(m)) canDo.delete(m);
}
return {
developMuscles: [...develop],
canDoMuscles: [...canDo],
difficultMuscles: [...difficult],
avoidMuscles: [...avoid],
};
}
export async function updateProfile(
prisma: PrismaClient,
userId: string,
data: UpdateProfileInput,
) {
const existing = await prisma.user.findUnique({ where: { id: userId } });
if (!existing) throw notFound('User not found');
const phone = data.phone;
if (phone && phone !== existing.phone) {
const phoneOwner = await prisma.user.findUnique({ where: { phone } });
if (phoneOwner) throw conflict('Phone already registered');
}
const muscles =
data.developMuscles !== undefined ||
data.canDoMuscles !== undefined ||
data.difficultMuscles !== undefined ||
data.avoidMuscles !== undefined
? resolveMuscleConflicts(
{
developMuscles: existing.developMuscles,
canDoMuscles: existing.canDoMuscles,
difficultMuscles: existing.difficultMuscles,
avoidMuscles: existing.avoidMuscles,
},
data,
)
: {};
const { availability, socialMedia, ...rest } = data;
const user = await prisma.user.update({
where: { id: userId },
data: {
...rest,
availability: toPrismaAvailability(availability),
socialMedia: toPrismaJson(socialMedia),
...muscles,
},
});
return { user: publicUser(user) };
}
export async function getBodyParameters(prisma: PrismaClient, userId: string) {
const [weight, circumferences] = await Promise.all([
prisma.bodyMeasurement.findMany({
where: { userId },
orderBy: { date: 'asc' },
}),
prisma.circumferenceMeasurement.findMany({
where: { userId },
orderBy: { date: 'asc' },
}),
]);
const byName = new Map<string, { name: string; points: { id: string; value: number; date: string }[] }>();
for (const c of circumferences) {
const entry = byName.get(c.name) ?? { name: c.name, points: [] };
entry.points.push({ id: c.id, value: c.value, date: c.date.toISOString() });
byName.set(c.name, entry);
}
return {
weight: weight.map((w) => ({ id: w.id, value: w.value, date: w.date.toISOString() })),
circumferences: [...byName.values()],
};
}
export async function addWeight(prisma: PrismaClient, userId: string, input: WeightInput) {
const entry = await prisma.bodyMeasurement.create({
data: { userId, value: input.value, date: input.date ? new Date(input.date) : new Date() },
});
return { id: entry.id, value: entry.value, date: entry.date };
}
export async function addCircumference(
prisma: PrismaClient,
userId: string,
input: CircumferenceInput,
) {
const entry = await prisma.circumferenceMeasurement.create({
data: {
userId,
name: input.name,
value: input.value,
date: input.date ? new Date(input.date) : new Date(),
},
});
return { id: entry.id, name: entry.name, value: entry.value, date: entry.date };
}
export async function deleteWeight(prisma: PrismaClient, userId: string, id: string) {
const entry = await prisma.bodyMeasurement.findFirst({ where: { id, userId } });
if (!entry) throw notFound('Measurement not found');
await prisma.bodyMeasurement.delete({ where: { id: entry.id } });
return { id: entry.id, value: entry.value, date: entry.date };
}
export async function deleteCircumference(prisma: PrismaClient, userId: string, id: string) {
const entry = await prisma.circumferenceMeasurement.findFirst({ where: { id, userId } });
if (!entry) throw notFound('Measurement not found');
await prisma.circumferenceMeasurement.delete({ where: { id: entry.id } });
return { id: entry.id, name: entry.name, value: entry.value, date: entry.date };
}
export async function getHistory(prisma: PrismaClient, userId: string) {
const sessions = await prisma.trainingSession.findMany({
where: { day: { week: { plan: { userId } } } },
orderBy: { startedAt: 'desc' },
take: 30,
include: {
day: {
select: {
date: true,
dayOfWeek: true,
week: { select: { plan: { select: { title: true } } } },
},
},
exercises: {
where: { removed: false },
orderBy: { order: 'asc' },
include: {
exercise: { select: { name: true, primaryMuscle: true } },
sets: { where: { removed: false }, orderBy: { index: 'asc' }, include: { planSet: true } },
comments: {
select: {
id: true,
body: true,
createdAt: true,
author: { select: { id: true, firstName: true, lastName: true } },
},
orderBy: { createdAt: 'asc' },
},
},
},
},
});
return {
sessions: sessions.map((s) => {
const exercises = s.exercises.filter((e) => !e.hidden);
let normTotal = 0;
let normDone = 0;
let bonus = 0;
for (const e of exercises) {
for (const st of e.sets) {
if (st.planSetId != null) {
normTotal += 1;
if (st.reps != null) normDone += 1;
} else if (st.reps != null) {
bonus += 1;
}
}
}
return {
id: s.id,
status: s.status,
startedAt: s.startedAt,
endedAt: s.endedAt,
date: s.day.date,
dayOfWeek: s.day.dayOfWeek,
plan: s.day.week.plan.title,
norm: { done: normDone, total: normTotal },
bonus,
deficit: normTotal - normDone,
exercises: exercises.map((e) => ({
id: e.id,
name: e.exercise.name,
muscle: e.exercise.primaryMuscle,
isExtra: e.planExerciseId === null,
comments: e.comments.map((c) => ({
id: c.id,
authorId: c.author.id,
authorName: [c.author.firstName, c.author.lastName].filter(Boolean).join(' ') || '—',
body: c.body,
createdAt: c.createdAt,
})),
sets: e.sets.map((st) => ({
index: st.index,
reps: st.reps,
rir: st.rir,
difficulty: st.difficulty,
planned: st.planSet
? {
reps: st.planSet.reps,
loadKg: st.planSet.loadKg,
restSec: st.planSet.restSec,
rir: st.planSet.rir,
}
: null,
})),
})),
};
}),
};
}

View File

@@ -0,0 +1,269 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, notFound } from '../lib/errors.js';
export interface ConversationListItem {
coachingId: string;
other: { id: string; firstName: string | null; lastName: string | null; nickname: string | null };
lastMessage: { body: string; createdAt: string; senderId: string } | null;
unreadCount: number;
}
/**
* The user must be a party of an ACTIVE coaching relation (either role).
*/
async function assertActiveRelation(prisma: PrismaClient, userId: string, coachingId: string) {
const coaching = await prisma.coaching.findUnique({ where: { id: coachingId } });
if (
!coaching ||
coaching.status !== 'ACTIVE' ||
(coaching.trainerId !== userId && coaching.userId !== userId)
) {
throw notFound('Conversation not found');
}
return coaching;
}
/**
* All ACTIVE coaching relations of the user (both roles) with the last message
* and the unread count (messages from the other side newer than lastReadAt).
* Batched — no N+1.
*/
export async function listConversations(prisma: PrismaClient, userId: string) {
const coachings = await prisma.coaching.findMany({
where: { status: 'ACTIVE', OR: [{ trainerId: userId }, { userId }] },
});
if (coachings.length === 0) return { conversations: [] as ConversationListItem[] };
const coachingIds = coachings.map((c) => c.id);
const otherIds = [...new Set(coachings.flatMap((c) => [c.trainerId, c.userId]))];
const [messages, reads, users] = await Promise.all([
prisma.message.findMany({ where: { coachingId: { in: coachingIds } }, orderBy: { createdAt: 'asc' } }),
prisma.conversationRead.findMany({ where: { userId } }),
prisma.user.findMany({
where: { id: { in: otherIds } },
select: { id: true, firstName: true, lastName: true, nickname: true },
}),
]);
const readByCoaching = new Map(reads.map((r) => [r.coachingId, r.lastReadAt]));
const lastByCoaching = new Map<string, (typeof messages)[number]>();
const unreadByCoaching = new Map<string, number>();
for (const m of messages) {
lastByCoaching.set(m.coachingId, m);
if (m.senderId !== userId) {
const lastReadAt = readByCoaching.get(m.coachingId);
if (!lastReadAt || m.createdAt > lastReadAt) {
unreadByCoaching.set(m.coachingId, (unreadByCoaching.get(m.coachingId) ?? 0) + 1);
}
}
}
const userById = new Map(users.map((u) => [u.id, u]));
const conversations: ConversationListItem[] = coachings.map((c) => {
const otherId = c.trainerId === userId ? c.userId : c.trainerId;
const other = userById.get(otherId);
const last = lastByCoaching.get(c.id) ?? null;
return {
coachingId: c.id,
other: other
? { id: other.id, firstName: other.firstName, lastName: other.lastName, nickname: other.nickname }
: { id: otherId, firstName: null, lastName: null, nickname: null },
lastMessage: last
? { body: last.body, createdAt: last.createdAt.toISOString(), senderId: last.senderId }
: null,
unreadCount: unreadByCoaching.get(c.id) ?? 0,
};
});
// newest conversation first; empty ones last
conversations.sort((a, b) => {
const at = a.lastMessage ? a.lastMessage.createdAt : '';
const bt = b.lastMessage ? b.lastMessage.createdAt : '';
return bt.localeCompare(at);
});
return { conversations };
}
export interface MessageAttachment {
sessionId: string;
sessionDate: string;
plan: string;
exercise: {
name: string;
sets: {
index: number;
reps: number | null;
rir: number | null;
planned: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null } | null;
}[];
} | null;
/** Only when exercise == null. */
exercises: { name: string; setsDone: number; setsTotal: number }[];
}
/**
* Thread of an ACTIVE relation (either party): the other side, the last 200
* messages (ascending) with computed attachments, and a read-mark upsert.
*/
export async function getConversation(prisma: PrismaClient, userId: string, coachingId: string) {
const coaching = await assertActiveRelation(prisma, userId, coachingId);
const role = coaching.trainerId === userId ? ('trainer' as const) : ('trainee' as const);
const otherId = coaching.trainerId === userId ? coaching.userId : coaching.trainerId;
const [other, messages] = await Promise.all([
prisma.user.findUnique({
where: { id: otherId },
select: { id: true, firstName: true, lastName: true, nickname: true },
}),
prisma.message.findMany({
where: { coachingId },
orderBy: { createdAt: 'desc' },
take: 200,
include: {
session: {
select: {
startedAt: true,
day: { select: { week: { select: { plan: { select: { title: true } } } } } },
exercises: {
where: { removed: false, hidden: false },
orderBy: { order: 'asc' },
include: {
exercise: { select: { name: true } },
sets: { where: { removed: false } },
},
},
},
},
sessionExercise: {
include: {
exercise: { select: { name: true } },
sets: {
where: { removed: false },
orderBy: { index: 'asc' },
include: { planSet: true },
},
},
},
},
}),
]);
const now = new Date();
await prisma.conversationRead.upsert({
where: { coachingId_userId: { coachingId, userId } },
update: { lastReadAt: now },
create: { coachingId, userId, lastReadAt: now },
});
return {
role,
other: other
? { id: other.id, firstName: other.firstName, lastName: other.lastName, nickname: other.nickname }
: { id: otherId, firstName: null, lastName: null, nickname: null },
messages: messages
.reverse()
.map((m) => ({
id: m.id,
senderId: m.senderId,
body: m.body,
createdAt: m.createdAt.toISOString(),
attachment: buildAttachment(m),
})),
};
}
function buildAttachment(m: {
sessionId: string | null;
session: {
startedAt: Date;
day: { week: { plan: { title: string } } };
exercises: {
exercise: { name: string };
sets: { reps: number | null }[];
}[];
} | null;
sessionExercise: {
exercise: { name: string };
sets: { index: number; reps: number | null; rir: number | null; planSet: { reps: number | null; loadKg: number | null; restSec: number | null; rir: number | null } | null }[];
} | null;
}): MessageAttachment | null {
if (!m.sessionId || !m.session) return null;
const attachment: MessageAttachment = {
sessionId: m.sessionId,
sessionDate: m.session.startedAt.toISOString(),
plan: m.session.day.week.plan.title,
exercise: null,
exercises: [],
};
if (m.sessionExercise) {
attachment.exercise = {
name: m.sessionExercise.exercise.name,
sets: m.sessionExercise.sets.map((st) => ({
index: st.index,
reps: st.reps,
rir: st.rir,
planned: st.planSet
? {
reps: st.planSet.reps,
loadKg: st.planSet.loadKg,
restSec: st.planSet.restSec,
rir: st.planSet.rir,
}
: null,
})),
};
} else {
attachment.exercises = m.session.exercises.map((e) => ({
name: e.exercise.name,
setsDone: e.sets.filter((st) => st.reps != null).length,
setsTotal: e.sets.length,
}));
}
return attachment;
}
/**
* Send a message in an ACTIVE relation. Attachment validation:
* sessionId must be a COMPLETED session of the trainee of this relation;
* sessionExerciseId (requires sessionId) must belong to that session and not be removed.
*/
export async function sendMessage(
prisma: PrismaClient,
userId: string,
coachingId: string,
input: { body: string; sessionId?: string; sessionExerciseId?: string },
) {
const coaching = await assertActiveRelation(prisma, userId, coachingId);
let sessionId: string | null = null;
let sessionExerciseId: string | null = null;
if (input.sessionId || input.sessionExerciseId) {
if (!input.sessionId) throw badRequest('sessionExerciseId requires sessionId');
const session = await prisma.trainingSession.findUnique({
where: { id: input.sessionId },
include: { day: { select: { week: { select: { plan: { select: { userId: true } } } } } } },
});
if (!session || session.status !== 'COMPLETED' || session.day.week.plan.userId !== coaching.userId) {
throw badRequest('Attachment must be a completed session of the trainee in this relation');
}
sessionId = session.id;
if (input.sessionExerciseId) {
const se = await prisma.sessionExercise.findFirst({
where: { id: input.sessionExerciseId, sessionId: session.id },
});
if (!se || se.removed) throw badRequest('Attachment exercise does not belong to this session');
sessionExerciseId = se.id;
}
}
const message = await prisma.message.create({
data: { coachingId, senderId: userId, body: input.body, sessionId, sessionExerciseId },
});
return { message };
}
/** Delete a message (author only). */
export async function deleteMessage(prisma: PrismaClient, userId: string, messageId: string) {
const message = await prisma.message.findFirst({ where: { id: messageId, senderId: userId } });
if (!message) throw notFound('Message not found');
await prisma.message.delete({ where: { id: message.id } });
}

300
api/src/services/plans.ts Normal file
View File

@@ -0,0 +1,300 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, conflict, notFound } from '../lib/errors.js';
import { isPrismaUnique } from '../lib/prisma.js';
export interface PlanSetInput {
index: number;
reps?: number | null;
loadKg?: number | null;
restSec?: number | null;
rir?: number | null;
difficulty?: number | null;
cardioBpm?: number | null;
timeSec?: number | null;
speed?: number | null;
}
export interface PlanExerciseInput {
exerciseId: string;
order: number;
sets: PlanSetInput[];
}
export interface PlanDayInput {
dayOfWeek: number;
exercises: PlanExerciseInput[];
}
export interface PlanWeekInput {
index: number;
days: PlanDayInput[];
}
export interface CreatePlanInput {
title: string;
weeksCount: number;
weeks: PlanWeekInput[];
/** Opcjonalna data startu (poniedziałek) — plan tworzony i aktywowany w jednym kroku. */
startDate?: string;
}
/**
* The requester may access the plan when they are its owner (the trainee) or a
* trainer with an ACTIVE coaching relation to the owner. Anything else — and a
* missing plan — is a 404 (no existence leak, matches assertActiveTrainee).
*/
async function assertPlanAccess(prisma: PrismaClient, planId: string, requesterId: string) {
const plan = await prisma.trainingPlan.findUnique({ where: { id: planId } });
if (!plan) throw notFound('Plan not found');
if (plan.userId === requesterId) return plan;
const coaching = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId: requesterId, userId: plan.userId } },
});
if (!coaching || coaching.status !== 'ACTIVE') throw notFound('Plan not found');
return plan;
}
async function validateExercises(prisma: PrismaClient, weeks: PlanWeekInput[]) {
const exerciseIds = new Set(
weeks.flatMap((w) => w.days.flatMap((d) => d.exercises.map((e) => e.exerciseId))),
);
if (exerciseIds.size === 0) return;
const exercises = await prisma.exercise.findMany({ where: { id: { in: [...exerciseIds] } } });
if (exercises.length !== exerciseIds.size) throw badRequest('Unknown exerciseId in plan');
}
function weekData(weeks: PlanWeekInput[]) {
return weeks.map((w) => ({
index: w.index,
days: {
create: w.days.map((d) => ({
dayOfWeek: d.dayOfWeek,
exercises: {
create: d.exercises.map((e) => ({
exerciseId: e.exerciseId,
order: e.order,
sets: { create: e.sets },
})),
},
})),
},
}));
}
export async function listPlans(prisma: PrismaClient, userId: string) {
const plans = await prisma.trainingPlan.findMany({
where: { userId },
orderBy: { createdAt: 'desc' },
include: {
creator: { select: { id: true, firstName: true, lastName: true } },
weeks: { select: { days: { select: { status: true } } } },
},
});
return {
plans: plans.map((p) => {
const days = (p.weeks ?? []).flatMap((w) => w.days);
const completed = days.filter((d) => d.status === 'COMPLETED').length;
const total = days.length;
const { weeks: _weeks, ...rest } = p;
return {
...rest,
progress: {
completed,
total,
percent: total > 0 ? Math.round((completed / total) * 100) : 0,
},
};
}),
};
}
export async function createPlan(
prisma: PrismaClient,
userId: string,
data: CreatePlanInput,
creatorId?: string,
) {
await validateExercises(prisma, data.weeks);
// Data startu: walidacja (poniedziałek) przed sprawdzeniem aktywnego planu.
const startOfStart = data.startDate ? parseStartMonday(data.startDate) : null;
if (startOfStart) await assertNoActivePlan(prisma, userId);
const plan = await prisma.trainingPlan.create({
data: {
title: data.title,
userId,
creatorId: creatorId ?? userId,
status: 'DRAFT',
weeksCount: data.weeksCount,
weeks: { create: weekData(data.weeks) },
},
});
if (startOfStart) await applyStartDate(prisma, plan.id, userId, startOfStart);
const updated = await prisma.trainingPlan.findUnique({ where: { id: plan.id } });
return {
plan: {
id: updated!.id,
title: updated!.title,
status: updated!.status,
weeksCount: updated!.weeksCount,
startDate: updated!.startDate,
},
};
}
export async function getPlan(prisma: PrismaClient, planId: string, userId: string) {
await assertPlanAccess(prisma, planId, userId);
const full = await prisma.trainingPlan.findUnique({
where: { id: planId },
include: {
weeks: {
orderBy: { index: 'asc' },
include: {
days: {
include: {
exercises: {
orderBy: { order: 'asc' },
include: { exercise: true, sets: { orderBy: { index: 'asc' } } },
},
moveLog: { orderBy: { movedAt: 'desc' } },
sessions: { orderBy: { startedAt: 'desc' } },
},
},
},
},
},
});
return { plan: full };
}
export async function updatePlan(
prisma: PrismaClient,
planId: string,
userId: string,
data: CreatePlanInput,
) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'DRAFT') throw badRequest('Only draft plans can be edited');
await validateExercises(prisma, data.weeks);
await prisma.$transaction(async (tx) => {
await tx.planWeek.deleteMany({ where: { planId: plan.id } });
await tx.trainingPlan.update({
where: { id: plan.id },
data: { title: data.title, weeksCount: data.weeksCount, weeks: { create: weekData(data.weeks) } },
});
});
return { ok: true };
}
export async function deletePlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'DRAFT') throw badRequest('Only draft plans can be deleted');
await prisma.trainingPlan.delete({ where: { id: plan.id } });
return { ok: true, title: plan.title };
}
export async function activatePlan(
prisma: PrismaClient,
planId: string,
userId: string,
rawStartDate: string,
) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status !== 'DRAFT') throw badRequest('Only draft plans can be activated');
// Walidacja daty (poniedziałek) przed sprawdzeniem aktywnego planu.
const startOfStart = parseStartMonday(rawStartDate);
// Ograniczenie "jeden aktywny plan" dotyczy właściciela planu (podopiecznego),
// nie inicjatora (trener może zarządzać planami wielu podopiecznych).
// Pre-check dla szybkiej ścieżki; rozstrzygające sprawdzenie jest atomowo
// w transakcji applyStartDate (blokada działa też przy równoległych żądaniach).
await assertNoActivePlan(prisma, plan.userId);
await applyStartDate(prisma, planId, plan.userId, startOfStart);
return { ok: true, title: plan.title };
}
function parseStartMonday(rawStartDate: string): Date {
const [y, m, d] = rawStartDate.split('-').map(Number);
if (!y || !m || !d) throw badRequest('Invalid start date');
const start = new Date(y, m - 1, d); // local date
if (start.getDay() !== 1) throw badRequest('Start date must be a Monday');
const startOfStart = new Date(start.getFullYear(), start.getMonth(), start.getDate());
// Tydzień startu: bieżący lub przyszły (jednostka = cały tydzień) — nie można
// dodawać treningów z datą wstecz.
const now = new Date();
const currentMonday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
currentMonday.setDate(currentMonday.getDate() - ((currentMonday.getDay() + 6) % 7));
if (startOfStart < currentMonday) throw badRequest('Start date cannot be in the past');
return startOfStart;
}
async function assertNoActivePlan(prisma: PrismaClient, userId: string) {
const existingActive = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
});
if (existingActive) throw conflict('User already has an active plan');
}
/**
* Sets the start date on a plan: computes training day dates and marks the
* plan ACTIVE. The date must already be validated (a Monday).
*
* The "one active plan per owner" rule is enforced ATOMICALLY inside the same
* transaction: the active-plan check and the status flip happen together, so
* two concurrent activations of different plans cannot both win.
*/
async function applyStartDate(
prisma: PrismaClient,
planId: string,
ownerId: string,
startOfStart: Date,
) {
const weeks = await prisma.planWeek.findMany({
where: { planId },
include: { days: true },
});
try {
await prisma.$transaction(async (tx) => {
const existingActive = await tx.trainingPlan.findFirst({
where: { userId: ownerId, status: 'ACTIVE' },
});
if (existingActive) throw conflict('User already has an active plan');
for (const week of weeks) {
for (const day of week.days) {
const date = new Date(startOfStart);
date.setDate(date.getDate() + week.index * 7 + (day.dayOfWeek - 1));
await tx.planDay.update({ where: { id: day.id }, data: { date } });
}
}
await tx.trainingPlan.update({
where: { id: planId },
data: { status: 'ACTIVE', startDate: startOfStart },
});
});
} catch (e) {
// Partial unique index (TrainingPlan_userId_active_key) — the last line of
// defence for truly concurrent activations that both passed the check above.
if (isPrismaUnique(e)) throw conflict('User already has an active plan');
throw e;
}
}
export async function abandonPlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status === 'COMPLETED' || plan.status === 'ABANDONED')
throw badRequest('Plan is already closed');
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'ABANDONED' },
});
return { ok: true, title: plan.title };
}
export async function completePlan(prisma: PrismaClient, planId: string, userId: string) {
const plan = await assertPlanAccess(prisma, planId, userId);
if (plan.status === 'COMPLETED' || plan.status === 'ABANDONED')
throw badRequest('Plan is already closed');
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'COMPLETED' },
});
return { ok: true, title: plan.title };
}

View File

@@ -0,0 +1,62 @@
import type { PrismaClient } from '@prisma/client';
import { logger } from '../lib/logger.js';
/**
* Background jobs (every 60s):
* 1. Auto-expire training days at 23:59 of their date -> skipped.
* 2. Auto-abandon sessions after 24h.
* 3. Auto-complete active plans when all days are completed/skipped.
* 4. Remove gym schedule exceptions whose date is in the past.
*/
export function startScheduler(prisma: PrismaClient): void {
const tick = async () => {
try {
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const expired = await prisma.planDay.updateMany({
where: { status: 'PLANNED', date: { lt: startOfToday } },
data: { status: 'SKIPPED', skippedAt: now },
});
if (expired.count > 0) logger.info({ count: expired.count }, 'Auto-expired days -> skipped');
const cutoff = new Date(now.getTime() - 24 * 60 * 60 * 1000);
const abandoned = await prisma.trainingSession.updateMany({
where: { status: 'IN_PROGRESS', startedAt: { lt: cutoff } },
data: { status: 'ABANDONED', endedAt: now },
});
if (abandoned.count > 0)
logger.info({ count: abandoned.count }, 'Auto-abandoned sessions (24h)');
const activePlans = await prisma.trainingPlan.findMany({
where: { status: 'ACTIVE' },
include: { weeks: { include: { days: true } } },
});
for (const plan of activePlans) {
const days = plan.weeks.flatMap((w) => w.days);
if (
days.length > 0 &&
days.every((d) => d.status === 'COMPLETED' || d.status === 'SKIPPED')
) {
await prisma.trainingPlan.update({
where: { id: plan.id },
data: { status: 'COMPLETED' },
});
logger.info({ planId: plan.id }, 'Plan auto-completed');
}
}
const removedExceptions = await prisma.gymException.deleteMany({
where: { date: { lt: startOfToday } },
});
if (removedExceptions.count > 0)
logger.info({ count: removedExceptions.count }, 'Removed past gym exceptions');
} catch (e) {
logger.error({ err: e }, 'Scheduler tick failed');
}
};
const interval = setInterval(tick, 60_000);
interval.unref();
void tick();
}

View File

@@ -0,0 +1,320 @@
import type { PrismaClient } from '@prisma/client';
import { badRequest, conflict, notFound } from '../lib/errors.js';
export interface UpdateExerciseInput {
hidden?: boolean;
removed?: boolean;
}
export interface UpdateSetInput {
reps?: number | null;
rir?: number | null;
difficulty?: number | null;
note?: string | null;
}
async function getSessionOwned(prisma: PrismaClient, sessionId: string, userId: string) {
const session = await prisma.trainingSession.findUnique({
where: { id: sessionId },
include: { day: { include: { week: { include: { plan: true } } } } },
});
if (!session || session.day.week.plan.userId !== userId) throw notFound('Session not found');
return session;
}
async function getExerciseOwned(prisma: PrismaClient, exerciseId: string, userId: string) {
const exercise = await prisma.sessionExercise.findUnique({
where: { id: exerciseId },
include: { session: { include: { day: { include: { week: { include: { plan: true } } } } } } },
});
if (!exercise || exercise.session.day.week.plan.userId !== userId)
throw notFound('Exercise not found');
return exercise;
}
export async function startSession(prisma: PrismaClient, dayId: string, userId: string) {
const day = await prisma.planDay.findUnique({
where: { id: dayId },
include: {
week: { include: { plan: true } },
exercises: {
orderBy: { order: 'asc' },
include: { sets: { orderBy: { index: 'asc' } } },
},
},
});
if (!day || day.week.plan.userId !== userId) throw notFound('Day not found');
if (day.status !== 'PLANNED') throw badRequest('Day is not in planned state');
const active = await prisma.trainingSession.findFirst({
where: { status: 'IN_PROGRESS', day: { week: { plan: { userId } } } },
orderBy: { startedAt: 'desc' },
});
if (active) throw conflict('You already have an active session');
const session = await prisma.trainingSession.create({ data: { dayId: day.id } });
if (day.exercises.length > 0) {
await prisma.sessionExercise.createMany({
data: day.exercises.map((e) => ({
sessionId: session.id,
exerciseId: e.exerciseId,
planExerciseId: e.id,
order: e.order,
})),
});
for (const e of day.exercises) {
if (e.sets.length === 0) continue;
const se = await prisma.sessionExercise.findFirst({
where: { sessionId: session.id, planExerciseId: e.id },
});
if (se) {
await prisma.sessionSet.createMany({
data: e.sets.map((ps) => ({
exerciseId: se.id,
planSetId: ps.id,
index: ps.index,
})),
});
}
}
}
return { sessionId: session.id, status: session.status };
}
/** Active (IN_PROGRESS) session of the user — for the sidebar link and dashboard shortcut. */
export async function getActiveSession(prisma: PrismaClient, userId: string) {
const session = await prisma.trainingSession.findFirst({
where: { status: 'IN_PROGRESS', day: { week: { plan: { userId } } } },
orderBy: { startedAt: 'desc' },
include: {
day: {
select: {
id: true,
date: true,
dayOfWeek: true,
week: { select: { plan: { select: { title: true } } } },
},
},
},
});
if (!session) return { session: null };
return {
session: {
id: session.id,
dayId: session.dayId,
dayDate: session.day.date,
dayOfWeek: session.day.dayOfWeek,
planTitle: session.day.week.plan.title,
startedAt: session.startedAt,
},
};
}
export async function getDay(prisma: PrismaClient, dayId: string, userId: string) {
const day = await prisma.planDay.findUnique({
where: { id: dayId },
include: {
week: { include: { plan: true } },
sessions: { orderBy: { startedAt: 'desc' } },
exercises: {
orderBy: { order: 'asc' },
include: { exercise: { select: { name: true, primaryMuscle: true } } },
},
},
});
if (!day || day.week.plan.userId !== userId) throw notFound('Day not found');
return {
day: {
id: day.id,
date: day.date,
status: day.status,
dayOfWeek: day.dayOfWeek,
planId: day.week.planId,
sessions: day.sessions.map((s) => ({ id: s.id, status: s.status, startedAt: s.startedAt })),
exercises: day.exercises.map((e) => ({
id: e.id,
name: e.exercise.name,
muscle: e.exercise.primaryMuscle,
})),
},
};
}
export async function getSession(prisma: PrismaClient, sessionId: string, userId: string) {
await getSessionOwned(prisma, sessionId, userId);
const session = await prisma.trainingSession.findUnique({
where: { id: sessionId },
include: {
day: {
include: {
week: { include: { plan: { select: { id: true, title: true, status: true } } } },
moveLog: { orderBy: { movedAt: 'desc' } },
},
},
exercises: {
orderBy: { order: 'asc' },
include: {
exercise: true,
sets: { where: { removed: false }, orderBy: { index: 'asc' } },
planExercise: { include: { sets: { orderBy: { index: 'asc' } } } },
},
},
},
});
return { session };
}
export async function addExercise(
prisma: PrismaClient,
sessionId: string,
userId: string,
exerciseId: string,
) {
const session = await getSessionOwned(prisma, sessionId, userId);
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
const template = await prisma.exercise.findUnique({ where: { id: exerciseId } });
if (!template) throw notFound('Exercise not found');
const maxOrder = await prisma.sessionExercise.aggregate({
where: { sessionId: session.id },
_max: { order: true },
});
const exercise = await prisma.sessionExercise.create({
data: {
sessionId: session.id,
exerciseId: template.id,
order: (maxOrder._max.order ?? -1) + 1,
},
});
return { exerciseId: exercise.id, order: exercise.order };
}
export async function updateExercise(
prisma: PrismaClient,
exerciseId: string,
userId: string,
data: UpdateExerciseInput,
) {
const exercise = await getExerciseOwned(prisma, exerciseId, userId);
if (exercise.session.status !== 'IN_PROGRESS')
throw badRequest('Session is not in progress');
await prisma.sessionExercise.update({
where: { id: exercise.id },
data,
});
return { ok: true };
}
/**
* Add an extra (bonus) set to a session exercise.
* Allowed only when every planned (norm) set of the session is recorded and no
* extra set is still pending — at most one pending extra set per session.
*/
export async function addSet(prisma: PrismaClient, exerciseId: string, userId: string) {
const exercise = await getExerciseOwned(prisma, exerciseId, userId);
if (exercise.session.status !== 'IN_PROGRESS')
throw badRequest('Session is not in progress');
const sets = await prisma.sessionSet.findMany({
where: { exercise: { sessionId: exercise.session.id }, removed: false },
});
const pendingNorm = sets.filter((s) => s.planSetId != null && s.reps == null).length;
if (pendingNorm > 0)
throw badRequest('All planned sets must be recorded before adding an extra set');
const pendingExtra = sets.filter((s) => s.planSetId == null && s.reps == null).length;
if (pendingExtra > 0)
throw badRequest('An extra set is already in progress');
const maxIndex = await prisma.sessionSet.aggregate({
where: { exerciseId: exercise.id },
_max: { index: true },
});
const set = await prisma.sessionSet.create({
data: { exerciseId: exercise.id, index: (maxIndex._max.index ?? -1) + 1 },
});
return { setId: set.id, index: set.index };
}
export async function updateSet(
prisma: PrismaClient,
setId: string,
userId: string,
data: UpdateSetInput,
) {
const set = await prisma.sessionSet.findUnique({
where: { id: setId },
include: { exercise: { include: { session: { include: { day: { include: { week: { include: { plan: true } } } } } } } } },
});
if (!set || set.exercise.session.day.week.plan.userId !== userId)
throw notFound('Set not found');
if (set.exercise.session.status !== 'IN_PROGRESS')
throw badRequest('Session is not in progress');
const updated = await prisma.sessionSet.update({
where: { id: set.id },
data,
});
return { set: updated };
}
/**
* Remove an extra (bonus) set from a session. Only extra sets (no planned
* counterpart) can be removed — and without consequence for the norm.
*/
export async function deleteSet(prisma: PrismaClient, setId: string, userId: string) {
const set = await prisma.sessionSet.findUnique({
where: { id: setId },
include: { exercise: { include: { session: { include: { day: { include: { week: { include: { plan: true } } } } } } } } },
});
if (!set || set.exercise.session.day.week.plan.userId !== userId)
throw notFound('Set not found');
if (set.planSetId != null)
throw badRequest('Only extra sets can be removed');
if (set.exercise.session.status !== 'IN_PROGRESS')
throw badRequest('Session is not in progress');
await prisma.sessionSet.update({ where: { id: set.id }, data: { removed: true } });
return { ok: true };
}
export async function completeSession(prisma: PrismaClient, sessionId: string, userId: string) {
const session = await getSessionOwned(prisma, sessionId, userId);
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
const exercises = await prisma.sessionExercise.findMany({
where: { sessionId: session.id, removed: false },
include: { sets: true },
});
// Only planned (norm) sets must be recorded; extra sets are a bonus and don't block.
const pending = exercises.reduce(
(n, e) => n + e.sets.filter((s) => !s.removed && s.planSetId != null && s.reps == null).length,
0,
);
if (pending > 0)
throw badRequest(`All planned sets must be recorded before completing the session (${pending} remaining)`);
const now = new Date();
await prisma.$transaction([
prisma.trainingSession.update({
where: { id: session.id },
data: { status: 'COMPLETED', endedAt: now },
}),
prisma.planDay.update({
where: { id: session.dayId },
data: { status: 'COMPLETED', completedAt: now },
}),
]);
return { ok: true };
}
/**
* Abandon an in-progress session. The day is marked SKIPPED so the abandoned
* training cannot be executed again (no new session can be started for it).
*/
export async function abandonSession(prisma: PrismaClient, sessionId: string, userId: string) {
const session = await getSessionOwned(prisma, sessionId, userId);
if (session.status !== 'IN_PROGRESS') throw badRequest('Session is not in progress');
const now = new Date();
await prisma.$transaction([
prisma.trainingSession.update({
where: { id: session.id },
data: { status: 'ABANDONED', endedAt: now },
}),
prisma.planDay.update({
where: { id: session.dayId },
data: { status: 'SKIPPED', skippedAt: now },
}),
]);
return { ok: true };
}

612
api/src/services/trainer.ts Normal file
View File

@@ -0,0 +1,612 @@
import type { PrismaClient } from '@prisma/client';
import { AppError, badRequest, conflict, forbidden, notFound } from '../lib/errors.js';
import { getKillstreak } from './killstreak.js';
import { getDashboard } from './dashboard.js';
import { getHistory } from './me.js';
import { getCalendar } from './calendar.js';
export const INVITATION_TTL_DAYS = 7;
export const MAX_PENDING_INVITATIONS = 10;
export type TraineeFlag = 'streak_reset' | 'no_session_7d' | 'high_deficit';
/**
* Attention flags for a trainee (pure — unit-testable):
* - streak_reset: killstreak is 0 although the plan already has resolved days,
* - no_session_7d: no completed session in the last 7 days (or ever),
* - high_deficit: more than 30% of planned sets left undone.
*/
export function computeFlags(args: {
hasActivePlan: boolean;
killstreak: number;
resolvedDays: number;
lastSessionAt: Date | null;
plannedSetCount: number;
donePlannedSetCount: number;
now?: Date;
}): TraineeFlag[] {
if (!args.hasActivePlan) return [];
const flags: TraineeFlag[] = [];
if (args.killstreak === 0 && args.resolvedDays > 0) flags.push('streak_reset');
const weekAgo = new Date((args.now ?? new Date()).getTime() - 7 * 24 * 60 * 60 * 1000);
if (!args.lastSessionAt || args.lastSessionAt < weekAgo) flags.push('no_session_7d');
if (
args.plannedSetCount > 0 &&
(args.plannedSetCount - args.donePlannedSetCount) / args.plannedSetCount > 0.3
) {
flags.push('high_deficit');
}
return flags;
}
export interface TraineeMetrics {
activePlan: { id: string; title: string; progress: { completed: number; total: number; percent: number } } | null;
killstreak: number;
lastSessionAt: string | null;
flags: TraineeFlag[];
}
/**
* Per-trainee metrics for the trainer's list/detail: active plan progress,
* killstreak, last completed session and attention flags.
*/
export async function computeTraineeMetrics(prisma: PrismaClient, userId: string): Promise<TraineeMetrics> {
const activePlan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
select: {
id: true,
title: true,
weeks: { select: { days: { select: { status: true } } } },
},
});
const killstreak = activePlan ? await getKillstreak(prisma, userId) : 0;
let progress: { completed: number; total: number; percent: number } | null = null;
let resolvedDays = 0;
if (activePlan) {
const days = activePlan.weeks.flatMap((w) => w.days);
const total = days.length;
const completed = days.filter((d) => d.status === 'COMPLETED' || d.status === 'SKIPPED').length;
resolvedDays = completed;
progress = { completed: completed, total, percent: total > 0 ? Math.round((completed / total) * 100) : 0 };
}
const lastSession = await prisma.trainingSession.findFirst({
where: { status: 'COMPLETED', day: { week: { plan: { userId } } } },
orderBy: { startedAt: 'desc' },
select: { startedAt: true },
});
let flags: TraineeFlag[] = [];
if (activePlan) {
const [plannedSetCount, donePlannedSetCount] = await Promise.all([
prisma.planSet.count({ where: { exercise: { day: { week: { planId: activePlan.id } } } } }),
prisma.sessionSet.count({
where: {
reps: { not: null },
planSetId: { not: null },
exercise: {
removed: false,
hidden: false,
session: { status: 'COMPLETED', day: { week: { planId: activePlan.id } } },
},
},
}),
]);
flags = computeFlags({
hasActivePlan: true,
killstreak,
resolvedDays,
lastSessionAt: lastSession ? lastSession.startedAt : null,
plannedSetCount,
donePlannedSetCount,
});
}
return {
activePlan: activePlan ? { id: activePlan.id, title: activePlan.title, progress: progress! } : null,
killstreak,
lastSessionAt: lastSession ? lastSession.startedAt.toISOString() : null,
flags,
};
}
async function hasTrainerRole(prisma: PrismaClient, userId: string): Promise<boolean> {
const membership = await prisma.gymMembership.findFirst({
where: { userId, roles: { has: 'TRAINER' } },
});
return !!membership;
}
export async function isTrainer(prisma: PrismaClient, userId: string): Promise<boolean> {
return hasTrainerRole(prisma, userId);
}
export interface UserSearchResult {
id: string;
firstName: string | null;
lastName: string | null;
nickname: string | null;
email: string;
phone: string | null;
gyms: { id: string; name: string }[];
}
/**
* Search users by first + last name (case-insensitive, partial match).
* Excludes the trainer and their current/pending trainees.
*/
export async function searchUsers(
prisma: PrismaClient,
trainerId: string,
firstName: string,
lastName: string,
) {
const relations = await prisma.coaching.findMany({
where: { trainerId, status: { in: ['ACTIVE', 'PENDING'] } },
select: { userId: true },
});
const excludeIds = new Set(relations.map((r) => r.userId));
excludeIds.add(trainerId);
const users = await prisma.user.findMany({
where: {
firstName: { contains: firstName, mode: 'insensitive' },
lastName: { contains: lastName, mode: 'insensitive' },
NOT: { id: { in: [...excludeIds] } },
},
select: {
id: true,
firstName: true,
lastName: true,
nickname: true,
email: true,
phone: true,
memberships: { select: { gym: { select: { id: true, name: true } } } },
},
take: 20,
orderBy: { createdAt: 'asc' },
});
return {
users: users.map((u) => ({
id: u.id,
firstName: u.firstName,
lastName: u.lastName,
nickname: u.nickname,
email: u.email,
phone: u.phone,
gyms: u.memberships.map((m) => m.gym),
})),
};
}
/**
* Send a coaching invitation. At least one party must hold the TRAINER role:
* - only the target is a trainer -> the target becomes the trainer (trainee invites trainer),
* - otherwise the requester is the trainer (trainer invites a trainee).
*/
export async function sendInvitation(
prisma: PrismaClient,
requesterId: string,
targetId: string,
) {
if (targetId === requesterId) throw badRequest('Cannot invite yourself');
const target = await prisma.user.findUnique({ where: { id: targetId } });
if (!target) throw notFound('User not found');
const [requesterIsTrainer, targetIsTrainer] = await Promise.all([
hasTrainerRole(prisma, requesterId),
hasTrainerRole(prisma, targetId),
]);
if (!requesterIsTrainer && !targetIsTrainer) throw badRequest('Trainer role required');
const trainerId = targetIsTrainer && !requesterIsTrainer ? targetId : requesterId;
const userId = trainerId === requesterId ? targetId : requesterId;
const existing = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId, userId } },
});
if (existing && (existing.status === 'PENDING' || existing.status === 'ACTIVE')) {
throw conflict('Invitation already exists');
}
for (const accountId of [requesterId, targetId]) {
const pending = await prisma.coaching.count({
where: { status: 'PENDING', OR: [{ trainerId: accountId }, { userId: accountId }] },
});
if (pending >= MAX_PENDING_INVITATIONS) throw conflict('Too many pending invitations');
}
const coaching = await prisma.coaching.create({
data: {
trainerId,
userId,
invitedBy: requesterId,
expiresAt: new Date(Date.now() + INVITATION_TTL_DAYS * 24 * 60 * 60 * 1000),
},
});
return { coaching, targetEmail: target.email };
}
interface PendingInvitation {
id: string;
trainerId: string;
userId: string;
invitedBy: string;
invitedAt: Date;
expiresAt: Date;
}
function otherPartyId(c: PendingInvitation, me: string): string {
return c.invitedBy === me ? (c.trainerId === me ? c.userId : c.trainerId) : c.invitedBy;
}
/** Pending (not expired) invitations involving the user — sent and received. */
export async function listInvitations(prisma: PrismaClient, userId: string) {
const now = new Date();
const coachings = await prisma.coaching.findMany({
where: {
status: 'PENDING',
expiresAt: { gt: now },
OR: [{ trainerId: userId }, { userId: userId }],
},
orderBy: { invitedAt: 'desc' },
});
const otherIds = [...new Set(coachings.map((c) => otherPartyId(c, userId)))];
const users = await prisma.user.findMany({
where: { id: { in: otherIds } },
select: { id: true, firstName: true, lastName: true, nickname: true, email: true, phone: true },
});
return {
invitations: coachings.map((c) => {
const otherId = otherPartyId(c, userId);
const u = users.find((x) => x.id === otherId);
return {
id: c.id,
direction: c.invitedBy === userId ? ('sent' as const) : ('received' as const),
other: u
? {
id: u.id,
firstName: u.firstName,
lastName: u.lastName,
nickname: u.nickname,
email: u.email,
phone: u.phone,
}
: null,
invitedAt: c.invitedAt.toISOString(),
expiresAt: c.expiresAt.toISOString(),
};
}),
};
}
async function loadPendingInvitation(prisma: PrismaClient, coachingId: string) {
const coaching = await prisma.coaching.findUnique({ where: { id: coachingId } });
if (!coaching) throw notFound('Invitation not found');
if (coaching.status !== 'PENDING') throw conflict('Invitation is not pending');
if (coaching.expiresAt <= new Date()) throw new AppError(410, 'GONE', 'Invitation expired');
return coaching;
}
/** Accept an invitation (invited party only). */
export async function acceptInvitation(prisma: PrismaClient, userId: string, coachingId: string) {
const coaching = await loadPendingInvitation(prisma, coachingId);
if (coaching.invitedBy === userId) throw forbidden('You sent this invitation');
const updated = await prisma.coaching.update({ where: { id: coachingId }, data: { status: 'ACTIVE' } });
return { coaching: updated };
}
/** Decline an invitation (invited party only). */
export async function declineInvitation(prisma: PrismaClient, userId: string, coachingId: string) {
const coaching = await loadPendingInvitation(prisma, coachingId);
if (coaching.invitedBy === userId) throw forbidden('You sent this invitation');
const updated = await prisma.coaching.update({ where: { id: coachingId }, data: { status: 'DECLINED' } });
return { coaching: updated };
}
/** Withdraw a pending invitation (sender only) — removes the relation. */
export async function withdrawInvitation(prisma: PrismaClient, userId: string, coachingId: string) {
const coaching = await prisma.coaching.findUnique({ where: { id: coachingId } });
if (!coaching) throw notFound('Invitation not found');
if (coaching.status !== 'PENDING') throw conflict('Invitation is not pending');
if (coaching.invitedBy !== userId) throw forbidden('Only the sender can withdraw the invitation');
await prisma.coaching.delete({ where: { id: coachingId } });
}
/** Active trainees of the trainer (global list, optional gym filter by trainee membership). */
export async function listTrainees(prisma: PrismaClient, trainerId: string, gymId?: string) {
const coachings = await prisma.coaching.findMany({
where: {
trainerId,
status: 'ACTIVE',
...(gymId ? { user: { memberships: { some: { gymId } } } } : {}),
},
include: {
user: {
select: {
id: true,
firstName: true,
lastName: true,
nickname: true,
memberships: { select: { gym: { select: { id: true, name: true } } } },
},
},
},
orderBy: { createdAt: 'asc' },
});
const trainees = await Promise.all(
coachings.map(async (c) => {
const metrics = await computeTraineeMetrics(prisma, c.user.id);
return {
user: {
id: c.user.id,
firstName: c.user.firstName,
lastName: c.user.lastName,
nickname: c.user.nickname,
},
gyms: c.user.memberships.map((m) => m.gym),
...metrics,
};
}),
);
return { trainees };
}
/** The trainer must have an ACTIVE coaching relation with the user. */
export async function assertActiveTrainee(prisma: PrismaClient, trainerId: string, userId: string) {
const coaching = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId, userId } },
});
if (!coaching || coaching.status !== 'ACTIVE') throw notFound('Trainee not found');
return coaching;
}
/**
* Restricted trainee detail: training metrics only (no body parameters, no profile).
*/
export async function getTraineeDetail(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
firstName: true,
lastName: true,
nickname: true,
socialMedia: true,
memberships: { select: { gym: { select: { id: true, name: true } } } },
},
});
if (!user) throw notFound('User not found');
const [dashboard, metrics] = await Promise.all([
getDashboard(prisma, userId),
computeTraineeMetrics(prisma, userId),
]);
return {
user: {
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
nickname: user.nickname,
},
socialMedia: user.socialMedia,
gyms: user.memberships.map((m) => m.gym),
activePlan: dashboard.activePlan,
progress: dashboard.progress,
killstreak: dashboard.killstreak,
nextTraining: dashboard.nextTraining,
extra: dashboard.extra,
missing: dashboard.missing,
lastSessionAt: metrics.lastSessionAt,
flags: metrics.flags,
};
}
/** Trainee session history with plan vs. actual (restricted: training data only). */
export async function getTraineeHistory(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
return getHistory(prisma, userId);
}
export interface MuscleReport {
muscle: string;
planned: { sets: number; reps: number };
actual: { sets: number; reps: number };
extra: { sets: number };
missing: { sets: number };
completionPct: number;
/** Weekly FocusArea range scaled to the plan duration (null when the muscle has no range). */
recommendedRange: { setsMin: number; setsMax: number } | null;
outOfRange: boolean;
}
export interface TraineeReport {
plan: { id: string; title: string; startDate: string | null } | null;
muscles: MuscleReport[];
days: { date: string; status: 'PLANNED' | 'COMPLETED' | 'SKIPPED'; moved: boolean }[];
}
/**
* Plan vs. actual per muscle group (decision 20) with the recommended volume
* range (decision 13) and plan days for the discipline heatmap.
*/
export async function getTraineeReport(prisma: PrismaClient, trainerId: string, userId: string): Promise<TraineeReport> {
await assertActiveTrainee(prisma, trainerId, userId);
const plan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
select: {
id: true,
title: true,
startDate: true,
weeksCount: true,
weeks: {
select: {
days: {
select: {
id: true,
date: true,
status: true,
moveLog: { select: { id: true } },
exercises: {
select: {
exercise: { select: { primaryMuscle: true } },
sets: { select: { reps: true } },
},
},
},
},
},
},
},
});
if (!plan) return { plan: null, muscles: [], days: [] };
const focusAreas = await prisma.focusArea.findMany({
select: { muscle: true, setsMin: true, setsMax: true },
});
const rangeByMuscle = new Map(focusAreas.map((f) => [f.muscle, f]));
const planned = new Map<string, { sets: number; reps: number }>();
const dayIds: string[] = [];
for (const week of plan.weeks) {
for (const day of week.days) {
dayIds.push(day.id);
for (const pe of day.exercises) {
const acc = planned.get(pe.exercise.primaryMuscle) ?? { sets: 0, reps: 0 };
for (const s of pe.sets) {
acc.sets += 1;
if (s.reps != null) acc.reps += s.reps;
}
planned.set(pe.exercise.primaryMuscle, acc);
}
}
}
const sessions = await prisma.trainingSession.findMany({
where: { status: 'COMPLETED', dayId: { in: dayIds } },
select: {
exercises: {
select: {
removed: true,
hidden: true,
exercise: { select: { primaryMuscle: true } },
sets: { select: { reps: true, planSetId: true } },
},
},
},
});
const actual = new Map<string, { sets: number; reps: number }>();
const extra = new Map<string, number>();
for (const session of sessions) {
for (const ex of session.exercises) {
if (ex.removed || ex.hidden) continue;
const muscle = ex.exercise.primaryMuscle;
for (const st of ex.sets) {
if (st.reps == null) continue;
if (st.planSetId != null) {
const acc = actual.get(muscle) ?? { sets: 0, reps: 0 };
acc.sets += 1;
acc.reps += st.reps;
actual.set(muscle, acc);
} else {
extra.set(muscle, (extra.get(muscle) ?? 0) + 1);
}
}
}
}
const muscles: MuscleReport[] = [...planned.entries()].map(([muscle, p]) => {
const a = actual.get(muscle) ?? { sets: 0, reps: 0 };
const e = extra.get(muscle) ?? 0;
const missing = Math.max(0, p.sets - a.sets);
const completionPct = p.sets > 0 ? Math.min(100, Math.round((a.sets / p.sets) * 100)) : 0;
const fa = rangeByMuscle.get(muscle);
const recommendedRange =
fa && fa.setsMin != null && fa.setsMax != null
? { setsMin: fa.setsMin * plan.weeksCount, setsMax: fa.setsMax * plan.weeksCount }
: null;
const outOfRange =
recommendedRange != null && (a.sets < recommendedRange.setsMin || a.sets > recommendedRange.setsMax);
return {
muscle,
planned: p,
actual: a,
extra: { sets: e },
missing: { sets: missing },
completionPct,
recommendedRange,
outOfRange,
};
});
const days = plan.weeks
.flatMap((w) => w.days)
.filter((d) => d.date != null)
.map((d) => ({
date: d.date!.toISOString(),
status: d.status,
moved: d.moveLog.length > 0,
}));
return {
plan: { id: plan.id, title: plan.title, startDate: plan.startDate ? plan.startDate.toISOString() : null },
muscles,
days,
};
}
/** Moved-day log (DayMove) for the trainee's active plan (decision 21). */
export async function getTraineeMoves(prisma: PrismaClient, trainerId: string, userId: string) {
await assertActiveTrainee(prisma, trainerId, userId);
const plan = await prisma.trainingPlan.findFirst({
where: { userId, status: 'ACTIVE' },
select: {
weeks: {
select: {
days: {
select: {
date: true,
moveLog: {
select: { dayId: true, fromDate: true, toDate: true, reason: true, movedAt: true },
orderBy: { movedAt: 'desc' },
},
},
},
},
},
},
});
const moves = plan
? plan.weeks.flatMap((w) =>
w.days.flatMap((d) =>
d.moveLog.map((m) => ({
dayId: m.dayId,
date: d.date ? d.date.toISOString() : null,
fromDate: m.fromDate.toISOString(),
toDate: m.toDate.toISOString(),
reason: m.reason,
movedAt: m.movedAt.toISOString(),
})),
),
)
: [];
return { moves };
}
/** Trainee calendar (days of the trainee's active plan in a month) for the trainer. */
export async function getTraineeCalendar(
prisma: PrismaClient,
trainerId: string,
userId: string,
month?: string,
) {
await assertActiveTrainee(prisma, trainerId, userId);
return getCalendar(prisma, userId, month);
}
/** Archive the trainer–trainee relation. */
export async function archiveTrainee(prisma: PrismaClient, trainerId: string, userId: string) {
const coaching = await prisma.coaching.findUnique({
where: { trainerId_userId: { trainerId, userId } },
});
if (!coaching || coaching.status !== 'ACTIVE') throw notFound('Trainee not found');
await prisma.coaching.update({ where: { id: coaching.id }, data: { status: 'ARCHIVED' } });
}

856
api/src/swagger.ts Normal file
View File

@@ -0,0 +1,856 @@
export const openapi: Record<string, unknown> = {
openapi: '3.0.0',
info: {
title: 'FitOS API',
version: '1.0.0',
description:
'FitOS — silnik planów treningowych. Autoryzacja: Bearer access token (15 min) + refresh token (httpOnly cookie).',
},
servers: [{ url: '/api/v1' }],
components: {
securitySchemes: {
bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
},
},
paths: {
'/auth/register': {
post: {
tags: ['Auth'],
summary: 'Self-registration (default role: member)',
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['email', 'password'],
properties: {
email: { type: 'string' },
password: { type: 'string', minLength: 8 },
firstName: { type: 'string' },
lastName: { type: 'string' },
},
},
},
},
},
responses: {
201: { description: 'Created (user + accessToken)' },
409: { description: 'Email already registered' },
},
},
},
'/auth/login': {
post: {
tags: ['Auth'],
summary: 'Login',
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['email', 'password'],
properties: {
email: { type: 'string' },
password: { type: 'string' },
},
},
},
},
},
responses: {
200: { description: 'OK (user + accessToken)' },
401: { description: 'Invalid credentials' },
},
},
},
'/auth/refresh': {
post: {
tags: ['Auth'],
summary: 'Refresh access token (refresh cookie)',
responses: {
200: { description: 'OK (accessToken)' },
401: { description: 'Invalid/revoked refresh token' },
},
},
},
'/auth/logout': {
post: { tags: ['Auth'], summary: 'Logout (clears refresh cookie)' },
},
'/me': {
get: {
tags: ['Profile'],
summary: 'Current user profile + gym memberships',
security: [{ bearerAuth: [] }],
},
patch: {
tags: ['Profile'],
summary: 'Update profile (personal data, priorities, exclusions, available time)',
security: [{ bearerAuth: [] }],
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
properties: {
firstName: { type: 'string' },
lastName: { type: 'string' },
age: { type: 'integer' },
heightCm: { type: 'number' },
availability: {
type: 'array',
description: '7 dni (Pon-Niedz), każdy null lub { start, end }',
items: {
type: 'object',
nullable: true,
properties: { start: { type: 'string' }, end: { type: 'string' } },
},
},
priorities: { type: 'string' },
exclusions: { type: 'string' },
developMuscles: { type: 'array', items: { type: 'string' } },
canDoMuscles: { type: 'array', items: { type: 'string' } },
difficultMuscles: { type: 'array', items: { type: 'string' } },
avoidMuscles: { type: 'array', items: { type: 'string' } },
},
},
},
},
},
},
},
'/me/active-session': {
get: {
tags: ['Sessions'],
summary: 'Active (IN_PROGRESS) training session of the current user, if any',
security: [{ bearerAuth: [] }],
},
},
'/me/body-parameters': {
get: {
tags: ['Profile'],
summary: 'Body parameters over time (weight + circumference series)',
security: [{ bearerAuth: [] }],
},
},
'/me/body-parameters/weight': {
post: {
tags: ['Profile'],
summary: 'Add weight measurement',
security: [{ bearerAuth: [] }],
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
required: ['value'],
properties: { value: { type: 'number' }, date: { type: 'string' } },
},
},
},
},
},
},
'/me/body-parameters/circumference': {
post: {
tags: ['Profile'],
summary: 'Add circumference measurement',
security: [{ bearerAuth: [] }],
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
required: ['name', 'value'],
properties: {
name: { type: 'string' },
value: { type: 'number' },
date: { type: 'string' },
},
},
},
},
},
},
},
'/exercises': {
get: {
tags: ['Exercises'],
summary: 'Exercise pool (MVP: full built-in pool)',
security: [{ bearerAuth: [] }],
},
},
'/exercises/{id}': {
get: {
tags: ['Exercises'],
summary: 'Exercise details',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/gyms': {
get: {
tags: ['Gyms'],
summary: "User's gyms (memberships)",
security: [{ bearerAuth: [] }],
},
post: {
tags: ['Gyms'],
summary: 'Create a gym (creator becomes its OWNER)',
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['name'],
properties: {
name: { type: 'string' },
location: { type: 'string' },
availability: {
type: 'array',
description: '7 dni (Pon-Niedz), każdy null lub { start, end }',
items: {
type: 'object',
nullable: true,
properties: { start: { type: 'string' }, end: { type: 'string' } },
},
},
capacity: { type: 'integer' },
},
},
},
},
},
},
},
'/gyms/all': {
get: {
tags: ['Gyms'],
summary: 'All gyms (for selecting an existing gym)',
security: [{ bearerAuth: [] }],
},
},
'/gyms/{gymId}/join': {
post: {
tags: ['Gyms'],
summary: 'Join an existing gym (MEMBER membership)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/gyms/{gymId}/equipment': {
post: {
tags: ['Gyms'],
summary: 'Add a catalog equipment item to a gym (owner only)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['equipmentId'],
properties: { equipmentId: { type: 'string' } },
},
},
},
},
},
},
'/gyms/{gymId}/equipment/{equipmentId}': {
delete: {
tags: ['Gyms'],
summary: 'Remove a catalog equipment item from a gym (owner only)',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'equipmentId', in: 'path', required: true, schema: { type: 'string' } },
],
},
},
'/gyms/{gymId}': {
patch: {
tags: ['Gyms'],
summary: 'Update a gym (owner only)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
required: false,
content: {
'application/json': {
schema: {
type: 'object',
properties: {
name: { type: 'string' },
location: { type: 'string', nullable: true },
availability: { type: 'array', nullable: true },
capacity: { type: 'integer', nullable: true },
},
},
},
},
},
},
delete: {
tags: ['Gyms'],
summary: 'Delete a gym (owner only). Memberships are removed; user plans are kept.',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/gyms/{gymId}/exceptions': {
get: {
tags: ['Gyms'],
summary: "List a gym's schedule exceptions (owner only)",
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
},
post: {
tags: ['Gyms'],
summary: 'Add a one-off schedule exception (owner only)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['date'],
properties: {
date: { type: 'string', description: 'YYYY-MM-DD' },
availability: {
type: 'object',
nullable: true,
description: 'null = closed, { start, end } = different hours',
properties: { start: { type: 'string' }, end: { type: 'string' } },
},
},
},
},
},
},
},
},
'/gyms/{gymId}/exceptions/{exceptionId}': {
delete: {
tags: ['Gyms'],
summary: 'Remove a schedule exception (owner only)',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'exceptionId', in: 'path', required: true, schema: { type: 'string' } },
],
},
},
'/admin/equipment': {
get: {
tags: ['Equipment'],
summary: 'List the equipment (machine/device) catalog (admin)',
security: [{ bearerAuth: [] }],
},
post: {
tags: ['Equipment'],
summary: 'Create an equipment catalog entry (admin)',
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['name'],
properties: { name: { type: 'string' }, description: { type: 'string', nullable: true } },
},
},
},
},
},
},
'/admin/equipment/{id}': {
patch: {
tags: ['Equipment'],
summary: 'Update an equipment catalog entry (admin)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
delete: {
tags: ['Equipment'],
summary: 'Delete an equipment catalog entry (admin)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/admin/exercises': {
get: {
tags: ['Exercises'],
summary: 'List exercise types with linked equipment (admin)',
security: [{ bearerAuth: [] }],
},
post: {
tags: ['Exercises'],
summary: 'Create an exercise type (admin)',
security: [{ bearerAuth: [] }],
},
},
'/admin/exercises/{id}': {
get: {
tags: ['Exercises'],
summary: 'Get an exercise type with linked equipment (admin)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
patch: {
tags: ['Exercises'],
summary: 'Update an exercise type (admin). equipmentIds replaces the linked set.',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
delete: {
tags: ['Exercises'],
summary: 'Delete an exercise type (admin). Fails if used in plans.',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/admin/gyms/{id}/equipment': {
post: {
tags: ['Admin'],
summary: 'Add a catalog equipment item to a gym (admin)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['equipmentId'],
properties: { equipmentId: { type: 'string' } },
},
},
},
},
},
},
'/admin/gyms/{id}/equipment/{equipmentId}': {
delete: {
tags: ['Admin'],
summary: 'Remove a catalog equipment item from a gym (admin)',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'equipmentId', in: 'path', required: true, schema: { type: 'string' } },
],
},
},
'/plans': {
get: {
tags: ['Plans'],
summary: "User's plans",
security: [{ bearerAuth: [] }],
},
post: {
tags: ['Plans'],
summary:
'Create plan: weeks -> days (dayOfWeek) -> exercises -> sets. Optional startDate (a Monday) creates and activates the plan in one step',
security: [{ bearerAuth: [] }],
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: 'object',
required: ['title', 'weeksCount', 'weeks'],
properties: {
title: { type: 'string' },
weeksCount: { type: 'integer', minimum: 1, maximum: 52 },
startDate: {
type: 'string',
description: 'YYYY-MM-DD, must be a Monday of the current or a future week',
},
weeks: {
type: 'array',
items: {
type: 'object',
required: ['index', 'days'],
properties: {
index: { type: 'integer', minimum: 0 },
days: {
type: 'array',
items: {
type: 'object',
required: ['dayOfWeek', 'exercises'],
properties: {
dayOfWeek: { type: 'integer', minimum: 1, maximum: 7 },
exercises: {
type: 'array',
items: {
type: 'object',
required: ['exerciseId', 'order', 'sets'],
properties: {
exerciseId: { type: 'string' },
order: { type: 'integer', minimum: 0 },
sets: {
type: 'array',
items: {
type: 'object',
required: ['index'],
properties: {
index: { type: 'integer' },
reps: { type: 'integer', nullable: true },
loadKg: { type: 'number', nullable: true },
restSec: { type: 'integer', nullable: true },
rir: { type: 'integer', nullable: true },
difficulty: { type: 'integer', nullable: true },
cardioBpm: { type: 'integer', nullable: true },
timeSec: { type: 'integer', nullable: true },
speed: { type: 'number', nullable: true },
},
},
},
},
},
},
},
},
},
},
},
},
},
},
},
},
},
},
},
'/plans/{id}': {
get: {
tags: ['Plans'],
summary: 'Plan details',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
patch: {
tags: ['Plans'],
summary: 'Replace plan structure (draft only)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
delete: {
tags: ['Plans'],
summary: 'Delete plan (draft only)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/plans/{id}/activate': {
post: {
tags: ['Plans'],
summary: 'Activate plan (startDate must be a Monday of the current or a future week)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
required: true,
content: {
'application/json': {
schema: { type: 'object', required: ['startDate'], properties: { startDate: { type: 'string' } } },
},
},
},
},
},
'/plans/{id}/abandon': {
post: {
tags: ['Plans'],
summary: 'Abandon plan',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/plans/{id}/complete': {
post: {
tags: ['Plans'],
summary: 'Manually archive plan',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/days/{dayId}/sessions': {
post: {
tags: ['Sessions'],
summary: 'Start session for a planned day (one active session per user)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'dayId', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/sessions/{id}': {
get: {
tags: ['Sessions'],
summary: 'Session details (exercises -> sets, planned parameters as parent)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/sessions/{id}/exercises': {
post: {
tags: ['Sessions'],
summary: 'Add exercise to session (kept for restore)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
required: true,
content: {
'application/json': {
schema: { type: 'object', required: ['exerciseId'], properties: { exerciseId: { type: 'string' } } },
},
},
},
},
},
'/sessions/exercises/{id}': {
patch: {
tags: ['Sessions'],
summary: 'Hide or remove exercise (data kept for restore)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
properties: { hidden: { type: 'boolean' }, removed: { type: 'boolean' } },
},
},
},
},
},
},
'/sessions/exercises/{id}/sets': {
post: {
tags: ['Sessions'],
summary: 'Add set to session exercise',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/sessions/sets/{id}': {
patch: {
tags: ['Sessions'],
summary: 'Record actual set results (reps, RIR, difficulty, note)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
properties: {
reps: { type: 'integer', nullable: true },
rir: { type: 'integer', nullable: true },
difficulty: { type: 'integer', nullable: true },
note: { type: 'string', nullable: true },
},
},
},
},
},
},
},
'/sessions/{id}/complete': {
post: {
tags: ['Sessions'],
summary: 'Complete session (requires all sets recorded; day -> completed)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/sessions/{id}/abandon': {
post: {
tags: ['Sessions'],
summary: 'Abandon session (data kept, day -> skipped, the training cannot be executed again)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/dashboard': {
get: {
tags: ['Dashboard'],
summary: 'Dashboard — killstreak, next training, plan progress',
security: [{ bearerAuth: [] }],
},
},
'/calendar': {
get: {
tags: ['Calendar'],
summary: 'Calendar — training days of the active plan in a month',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'month', in: 'query', schema: { type: 'string' }, description: 'YYYY-MM (default: current)' },
],
},
},
'/admin/gyms': {
get: {
tags: ['Admin'],
summary: 'List gyms (admin)',
security: [{ bearerAuth: [] }],
},
post: {
tags: ['Admin'],
summary: 'Create gym (admin)',
security: [{ bearerAuth: [] }],
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
required: ['name'],
properties: {
name: { type: 'string' },
location: { type: 'string' },
availability: {
type: 'array',
description: '7 dni (Pon-Niedz), każdy null lub { start, end }',
items: {
type: 'object',
nullable: true,
properties: { start: { type: 'string' }, end: { type: 'string' } },
},
},
capacity: { type: 'integer' },
},
},
},
},
},
},
},
'/admin/gyms/{id}': {
patch: {
tags: ['Admin'],
summary: 'Update gym (admin)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
delete: {
tags: ['Admin'],
summary: 'Delete gym (admin; memberships removed, plans kept)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/admin/users': {
get: {
tags: ['Admin'],
summary: 'List users (admin, optional ?search=)',
security: [{ bearerAuth: [] }],
},
post: {
tags: ['Admin'],
summary: 'Create user (admin)',
security: [{ bearerAuth: [] }],
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
required: ['email', 'password'],
properties: {
email: { type: 'string' },
password: { type: 'string' },
firstName: { type: 'string' },
lastName: { type: 'string' },
age: { type: 'integer' },
isAdmin: { type: 'boolean' },
},
},
},
},
},
},
},
'/admin/users/{id}': {
patch: {
tags: ['Admin'],
summary: 'Update user (admin; role change revokes JWT via token_version)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
delete: {
tags: ['Admin'],
summary: 'Delete user (admin; plans/sessions cascade-deleted)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
},
},
'/admin/users/{id}/memberships': {
post: {
tags: ['Admin'],
summary: 'Assign gym membership with roles (admin)',
security: [{ bearerAuth: [] }],
parameters: [{ name: 'id', in: 'path', required: true, schema: { type: 'string' } }],
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
required: ['gymId', 'roles'],
properties: {
gymId: { type: 'string' },
roles: {
type: 'array',
items: { type: 'string', enum: ['OWNER', 'TRAINER', 'MEMBER'] },
minItems: 1,
},
},
},
},
},
},
},
},
'/admin/users/{id}/memberships/{gymId}': {
patch: {
tags: ['Admin'],
summary: 'Change gym membership roles (admin)',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
],
requestBody: {
content: {
'application/json': {
schema: {
type: 'object',
required: ['roles'],
properties: {
roles: {
type: 'array',
items: { type: 'string', enum: ['OWNER', 'TRAINER', 'MEMBER'] },
minItems: 1,
},
},
},
},
},
},
},
delete: {
tags: ['Admin'],
summary: 'Remove gym membership (admin)',
security: [{ bearerAuth: [] }],
parameters: [
{ name: 'id', in: 'path', required: true, schema: { type: 'string' } },
{ name: 'gymId', in: 'path', required: true, schema: { type: 'string' } },
],
},
},
},
};