385 lines
11 KiB
TypeScript
385 lines
11 KiB
TypeScript
import { Prisma } from '@prisma/client';
|
|
import type { PrismaClient } from '@prisma/client';
|
|
import { publicUser } from '../lib/publicUser.js';
|
|
import { conflict, notFound } from '../lib/errors.js';
|
|
import { isPrismaUnique } from '../lib/prisma.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 type CircumferenceSide = 'left' | 'right';
|
|
|
|
/** Znane typy pomiarów obwodu (kolejność zgodna z listą na froncie). */
|
|
export const CIRCUMFERENCE_TYPE_IDS = [
|
|
'chest',
|
|
'waist',
|
|
'hips',
|
|
'neck',
|
|
'biceps',
|
|
'forearm',
|
|
'thigh',
|
|
'calf',
|
|
] as const;
|
|
|
|
export interface CircumferenceInput {
|
|
typeId: string;
|
|
side?: CircumferenceSide | null;
|
|
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;
|
|
try {
|
|
const user = await prisma.user.update({
|
|
where: { id: userId },
|
|
data: {
|
|
...rest,
|
|
availability: toPrismaAvailability(availability),
|
|
socialMedia: toPrismaJson(socialMedia),
|
|
...muscles,
|
|
},
|
|
});
|
|
return { user: publicUser(user) };
|
|
} catch (e) {
|
|
// wyścig z pre-checkiem: inny użytkownik zdążył zapisać ten sam numer
|
|
if (isPrismaUnique(e)) throw conflict('Phone already registered');
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
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' },
|
|
}),
|
|
]);
|
|
interface Series {
|
|
typeId: string | null;
|
|
side: string | null;
|
|
/** Znacząca tylko dla starszych pomiarów (typeId = null) — zachowana swobodna nazwa. */
|
|
name: string | null;
|
|
points: { id: string; value: number; date: string }[];
|
|
}
|
|
const byKey = new Map<string, Series>();
|
|
for (const c of circumferences) {
|
|
// Nowe: grupujemy po (typeId, side). Starsze bez typeId: po zachowanej nazwie.
|
|
const key = c.typeId ? `t:${c.typeId}:${c.side ?? ''}` : `n:${c.name ?? ''}`;
|
|
let entry = byKey.get(key);
|
|
if (!entry) {
|
|
entry = {
|
|
typeId: c.typeId,
|
|
side: c.typeId ? c.side : null,
|
|
name: c.typeId ? null : c.name,
|
|
points: [],
|
|
};
|
|
byKey.set(key, entry);
|
|
}
|
|
entry.points.push({ id: c.id, value: c.value, date: c.date.toISOString() });
|
|
}
|
|
return {
|
|
weight: weight.map((w) => ({ id: w.id, value: w.value, date: w.date.toISOString() })),
|
|
circumferences: [...byKey.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,
|
|
typeId: input.typeId,
|
|
side: input.side ?? null,
|
|
value: input.value,
|
|
date: input.date ? new Date(input.date) : new Date(),
|
|
},
|
|
});
|
|
return {
|
|
id: entry.id,
|
|
typeId: entry.typeId,
|
|
side: entry.side,
|
|
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,
|
|
typeId: entry.typeId,
|
|
side: entry.side,
|
|
name: entry.name,
|
|
value: entry.value,
|
|
date: entry.date,
|
|
};
|
|
}
|
|
|
|
export async function getHistory(prisma: PrismaClient, userId: string, month?: string) {
|
|
// month = 'YYYY-MM' — sesje, których dzień treningowy leży w tym miesiącu
|
|
const where: Prisma.TrainingSessionWhereInput = {
|
|
day: { week: { plan: { userId } } },
|
|
};
|
|
if (month) {
|
|
const [year, mon] = month.split('-').map(Number);
|
|
where.day = {
|
|
week: { plan: { userId } },
|
|
date: { gte: new Date(year, mon - 1, 1), lt: new Date(year, mon, 1) },
|
|
};
|
|
}
|
|
const sessions = await prisma.trainingSession.findMany({
|
|
where,
|
|
orderBy: { startedAt: 'desc' },
|
|
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, nameEn: 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,
|
|
nameEn: e.exercise.nameEn,
|
|
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,
|
|
// komentarz trenującego przy serii (widoczny też dla trenera)
|
|
note: st.note,
|
|
planned: st.planSet
|
|
? {
|
|
reps: st.planSet.reps,
|
|
loadKg: st.planSet.loadKg,
|
|
restSec: st.planSet.restSec,
|
|
rir: st.planSet.rir,
|
|
}
|
|
: null,
|
|
})),
|
|
})),
|
|
};
|
|
}),
|
|
};
|
|
}
|