230 lines
6.5 KiB
TypeScript
230 lines
6.5 KiB
TypeScript
import request from 'supertest';
|
|
import bcrypt from 'bcryptjs';
|
|
import { createApp } from '../src/app.js';
|
|
import { prisma } from '../src/lib/prisma.js';
|
|
import { signAccessToken } from '../src/lib/jwt.js';
|
|
|
|
export function buildApp() {
|
|
return request(createApp({ prisma }));
|
|
}
|
|
|
|
export function buildAgent() {
|
|
return request.agent(createApp({ prisma }));
|
|
}
|
|
|
|
let counter = 0;
|
|
export function rand(): string {
|
|
counter += 1;
|
|
return `${Date.now().toString(36)}${counter.toString(36)}${Math.random().toString(36).slice(2, 8)}`;
|
|
}
|
|
|
|
export const PASSWORD = 'Password123!';
|
|
|
|
export async function createUser(overrides: {
|
|
email?: string;
|
|
password?: string;
|
|
isAdmin?: boolean;
|
|
firstName?: string;
|
|
lastName?: string;
|
|
phone?: string;
|
|
} = {}) {
|
|
const email = overrides.email ?? `user-${rand()}@test.local`;
|
|
const password = overrides.password ?? PASSWORD;
|
|
const user = await prisma.user.create({
|
|
data: {
|
|
email,
|
|
passwordHash: await bcrypt.hash(password, 10),
|
|
isAdmin: overrides.isAdmin ?? false,
|
|
firstName: overrides.firstName,
|
|
lastName: overrides.lastName,
|
|
phone: overrides.phone,
|
|
},
|
|
});
|
|
return { user, password };
|
|
}
|
|
|
|
/**
|
|
* Create a user and mint a valid access token directly (no /auth/login call).
|
|
* Use this in test files that would otherwise exceed the auth rate limit (20/15min).
|
|
*/
|
|
export async function createUserWithToken(
|
|
overrides: Parameters<typeof createUser>[0] = {},
|
|
): Promise<{ user: Awaited<ReturnType<typeof createUser>>['user']; token: string }> {
|
|
const { user } = await createUser(overrides);
|
|
const token = signAccessToken(user.id, user.tokenVersion);
|
|
return { user, token };
|
|
}
|
|
|
|
export async function createExercise(overrides: { slug?: string; name?: string } = {}) {
|
|
const slug = overrides.slug ?? `exercise-${rand()}`;
|
|
return prisma.exercise.create({
|
|
data: {
|
|
slug,
|
|
name: overrides.name ?? `Exercise ${slug}`,
|
|
primaryMuscle: 'chest',
|
|
secondaryMuscles: ['triceps'],
|
|
description: 'Test exercise',
|
|
howTo: 'Test how-to',
|
|
commonMistakes: 'Test mistakes',
|
|
difficulty: 3,
|
|
source: 'BUILTIN',
|
|
},
|
|
});
|
|
}
|
|
|
|
/** Create (or fetch) an equipment catalog entry by name. */
|
|
export async function createEquipment(name: string) {
|
|
return prisma.equipment.upsert({
|
|
where: { name },
|
|
update: {},
|
|
create: { name },
|
|
});
|
|
}
|
|
|
|
export interface SeedDay {
|
|
dayOfWeek: number;
|
|
date?: Date | null;
|
|
status?: 'PLANNED' | 'COMPLETED' | 'SKIPPED';
|
|
exercises?: {
|
|
exerciseId: string;
|
|
order: number;
|
|
sets?: { index: number; reps?: number | null; loadKg?: number | null; restSec?: number | null }[];
|
|
}[];
|
|
}
|
|
|
|
export interface SeedWeek {
|
|
index: number;
|
|
days: SeedDay[];
|
|
}
|
|
|
|
export async function seedPlan(opts: {
|
|
userId: string;
|
|
title?: string;
|
|
status?: 'DRAFT' | 'ACTIVE' | 'COMPLETED' | 'ABANDONED';
|
|
startDate?: Date | null;
|
|
weeks?: SeedWeek[];
|
|
}) {
|
|
const weeks = opts.weeks ?? [{ index: 0, days: [] }];
|
|
return prisma.trainingPlan.create({
|
|
data: {
|
|
title: opts.title ?? `Plan ${rand()}`,
|
|
userId: opts.userId,
|
|
creatorId: opts.userId,
|
|
status: opts.status ?? 'DRAFT',
|
|
weeksCount: weeks.length,
|
|
startDate: opts.startDate ?? null,
|
|
weeks: {
|
|
create: weeks.map((w) => ({
|
|
index: w.index,
|
|
days: {
|
|
create: w.days.map((d) => ({
|
|
dayOfWeek: d.dayOfWeek,
|
|
date: d.date ?? null,
|
|
status: d.status ?? 'PLANNED',
|
|
exercises: {
|
|
create: (d.exercises ?? []).map((e) => ({
|
|
exerciseId: e.exerciseId,
|
|
order: e.order,
|
|
sets: {
|
|
create: (e.sets ?? []).map((s) => ({
|
|
index: s.index,
|
|
reps: s.reps ?? null,
|
|
loadKg: s.loadKg ?? null,
|
|
restSec: s.restSec ?? null,
|
|
})),
|
|
},
|
|
})),
|
|
},
|
|
})),
|
|
},
|
|
})),
|
|
},
|
|
},
|
|
include: {
|
|
weeks: {
|
|
orderBy: { index: 'asc' },
|
|
include: {
|
|
days: {
|
|
include: {
|
|
exercises: { orderBy: { order: 'asc' }, include: { sets: { orderBy: { index: 'asc' } }, exercise: true } },
|
|
sessions: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function seedSession(
|
|
dayId: string,
|
|
opts: {
|
|
status?: 'IN_PROGRESS' | 'COMPLETED' | 'ABANDONED';
|
|
startedAt?: Date;
|
|
exercises?: {
|
|
exerciseId: string;
|
|
planExerciseId?: string | null;
|
|
order: number;
|
|
hidden?: boolean;
|
|
removed?: boolean;
|
|
sets?: {
|
|
planSetId?: string | null;
|
|
reps?: number | null;
|
|
rir?: number | null;
|
|
index?: number;
|
|
}[];
|
|
}[];
|
|
} = {},
|
|
) {
|
|
return prisma.trainingSession.create({
|
|
data: {
|
|
dayId,
|
|
status: opts.status ?? 'IN_PROGRESS',
|
|
...(opts.startedAt ? { startedAt: opts.startedAt } : {}),
|
|
exercises: {
|
|
create: (opts.exercises ?? []).map((e) => ({
|
|
exerciseId: e.exerciseId,
|
|
planExerciseId: e.planExerciseId ?? null,
|
|
order: e.order,
|
|
hidden: e.hidden ?? false,
|
|
removed: e.removed ?? false,
|
|
sets: {
|
|
create: (e.sets ?? []).map((s, i) => ({
|
|
planSetId: s.planSetId ?? null,
|
|
reps: s.reps ?? null,
|
|
rir: s.rir ?? null,
|
|
index: s.index ?? i,
|
|
})),
|
|
},
|
|
})),
|
|
},
|
|
},
|
|
include: {
|
|
exercises: {
|
|
orderBy: { order: 'asc' },
|
|
include: {
|
|
sets: { orderBy: { index: 'asc' } },
|
|
planExercise: { include: { sets: { orderBy: { index: 'asc' } } } },
|
|
exercise: true,
|
|
},
|
|
},
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function registerViaApi(email?: string, password?: string) {
|
|
const app = buildApp();
|
|
const res = await app
|
|
.post('/api/v1/auth/register')
|
|
.send({ email: email ?? `api-${rand()}@test.local`, password: password ?? PASSWORD });
|
|
if (res.status !== 201) throw new Error(`register failed: ${res.status} ${JSON.stringify(res.body)}`);
|
|
return { token: res.body.accessToken as string, user: res.body.user as { id: string; email: string } };
|
|
}
|
|
|
|
export async function loginViaApi(email: string, password: string) {
|
|
const app = buildApp();
|
|
const res = await app.post('/api/v1/auth/login').send({ email, password });
|
|
if (res.status !== 200) throw new Error(`login failed: ${res.status} ${JSON.stringify(res.body)}`);
|
|
return { token: res.body.accessToken as string, user: res.body.user as { id: string; email: string } };
|
|
}
|