Files
FitOS/api/src/services/exercises.ts

159 lines
5.3 KiB
TypeScript

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[];
hasReps?: boolean;
hasLoad?: boolean;
hasRest?: boolean;
hasSets?: boolean;
hasRir?: boolean;
hasDifficulty?: boolean;
hasCardio?: boolean;
hasTime?: boolean;
hasSpeed?: boolean;
}
const exerciseInclude = {
equipment: { orderBy: { name: 'asc' } },
_count: { select: { planExercises: true } },
} satisfies Prisma.ExerciseInclude;
/** Płaski licznik użyć w planach (zamiast surowego `_count`). */
function withPlanCount<T extends { _count: { planExercises: number } }>(exercise: T) {
const { _count, ...rest } = exercise;
return { ...rest, planExercisesCount: _count.planExercises };
}
/** List all exercise types with their linked equipment and plan-usage count. */
export async function listExercises(prisma: PrismaClient) {
const exercises = await prisma.exercise.findMany({
include: exerciseInclude,
orderBy: { name: 'asc' },
});
return { exercises: exercises.map(withPlanCount) };
}
/** Get a single exercise type with its linked equipment and plan-usage count. */
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: withPlanCount(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',
// undefined → Prisma default (has* pozostają przy domyślnych kombinacjach)
hasReps: data.hasReps,
hasLoad: data.hasLoad,
hasRest: data.hasRest,
hasSets: data.hasSets,
hasRir: data.hasRir,
hasDifficulty: data.hasDifficulty,
hasCardio: data.hasCardio,
hasTime: data.hasTime,
hasSpeed: data.hasSpeed,
equipment,
},
include: exerciseInclude,
});
return { exercise: withPlanCount(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,
hasReps: data.hasReps,
hasLoad: data.hasLoad,
hasRest: data.hasRest,
hasSets: data.hasSets,
hasRir: data.hasRir,
hasDifficulty: data.hasDifficulty,
hasCardio: data.hasCardio,
hasTime: data.hasTime,
hasSpeed: data.hasSpeed,
...(data.equipmentIds !== undefined
? { equipment: { set: data.equipmentIds.map((eid) => ({ id: eid })) } }
: {}),
},
include: exerciseInclude,
});
return { exercise: withPlanCount(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;
}
}