Baseline: stan przed refaktoryzacja struktury
This commit is contained in:
568
api/src/services/admin.ts
Normal file
568
api/src/services/admin.ts
Normal 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
86
api/src/services/audit.ts
Normal 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
63
api/src/services/auth.ts
Normal 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) };
|
||||
}
|
||||
46
api/src/services/calendar.ts
Normal file
46
api/src/services/calendar.ts
Normal 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,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
90
api/src/services/comments.ts
Normal file
90
api/src/services/comments.ts
Normal 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 } });
|
||||
}
|
||||
104
api/src/services/dashboard.ts
Normal file
104
api/src/services/dashboard.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
87
api/src/services/equipment.ts
Normal file
87
api/src/services/equipment.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
15
api/src/services/exercisePool.ts
Normal file
15
api/src/services/exercisePool.ts
Normal 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 };
|
||||
}
|
||||
212
api/src/services/exerciseProgress.ts
Normal file
212
api/src/services/exerciseProgress.ts
Normal 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);
|
||||
}
|
||||
123
api/src/services/exercises.ts
Normal file
123
api/src/services/exercises.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
61
api/src/services/focusAreas.ts
Normal file
61
api/src/services/focusAreas.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
73
api/src/services/focusChain.ts
Normal file
73
api/src/services/focusChain.ts
Normal 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
1033
api/src/services/gyms.ts
Normal file
File diff suppressed because it is too large
Load Diff
80
api/src/services/killstreak.ts
Normal file
80
api/src/services/killstreak.ts
Normal 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
314
api/src/services/me.ts
Normal 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,
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
269
api/src/services/messages.ts
Normal file
269
api/src/services/messages.ts
Normal 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
300
api/src/services/plans.ts
Normal 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 };
|
||||
}
|
||||
62
api/src/services/scheduler.ts
Normal file
62
api/src/services/scheduler.ts
Normal 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();
|
||||
}
|
||||
320
api/src/services/sessions.ts
Normal file
320
api/src/services/sessions.ts
Normal 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
612
api/src/services/trainer.ts
Normal 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' } });
|
||||
}
|
||||
Reference in New Issue
Block a user