Code maintainability fixes

This commit is contained in:
AG
2025-12-06 11:32:40 +02:00
parent a13ef9f479
commit 4106f3b783
23 changed files with 1775 additions and 796 deletions

View File

@@ -25,12 +25,26 @@ router.get('/', async (req: any, res) => {
try {
const userId = req.user.userId;
const plans = await prisma.workoutPlan.findMany({
where: { userId }
where: { userId },
include: {
planExercises: {
include: { exercise: true },
orderBy: { order: 'asc' }
}
},
orderBy: { createdAt: 'desc' }
});
const mappedPlans = plans.map((p: any) => ({
...p,
steps: p.exercises ? JSON.parse(p.exercises) : []
steps: p.planExercises.map((pe: any) => ({
id: pe.id,
exerciseId: pe.exerciseId,
exerciseName: pe.exercise.name,
exerciseType: pe.exercise.type,
isWeighted: pe.isWeighted,
// Add default properties if needed by PlannedSet interface
}))
}));
res.json(mappedPlans);
@@ -46,28 +60,71 @@ router.post('/', async (req: any, res) => {
const userId = req.user.userId;
const { id, name, description, steps } = req.body;
const exercisesJson = JSON.stringify(steps || []);
// Steps array contains PlannedSet items
// We need to transact: create/update plan, then replace exercises
const existing = await prisma.workoutPlan.findUnique({ where: { id } });
await prisma.$transaction(async (tx) => {
// Upsert plan
let plan = await tx.workoutPlan.findUnique({ where: { id } });
if (existing) {
const updated = await prisma.workoutPlan.update({
where: { id },
data: { name, description, exercises: exercisesJson }
});
res.json({ ...updated, steps: steps || [] });
} else {
const created = await prisma.workoutPlan.create({
data: {
id,
userId,
name,
description,
exercises: exercisesJson
if (plan) {
await tx.workoutPlan.update({
where: { id },
data: { name, description }
});
// Delete existing plan exercises
await tx.planExercise.deleteMany({ where: { planId: id } });
} else {
await tx.workoutPlan.create({
data: {
id,
userId,
name,
description
}
});
}
// Create new plan exercises
if (steps && steps.length > 0) {
await tx.planExercise.createMany({
data: steps.map((step: any, index: number) => ({
planId: id,
exerciseId: step.exerciseId,
order: index,
isWeighted: step.isWeighted || false
}))
});
}
});
// Return the updated plan structure
// Since we just saved it, we can mirror back what was sent or re-fetch.
// Re-fetching ensures DB state consistency.
const savedPlan = await prisma.workoutPlan.findUnique({
where: { id },
include: {
planExercises: {
include: { exercise: true },
orderBy: { order: 'asc' }
}
});
res.json({ ...created, steps: steps || [] });
}
}
});
if (!savedPlan) throw new Error("Plan failed to save");
const mappedPlan = {
...savedPlan,
steps: savedPlan.planExercises.map((pe: any) => ({
id: pe.id,
exerciseId: pe.exerciseId,
exerciseName: pe.exercise.name,
exerciseType: pe.exercise.type,
isWeighted: pe.isWeighted
}))
};
res.json(mappedPlan);
} catch (error) {
console.error('Error saving plan:', error);
res.status(500).json({ error: 'Server error' });

View File

@@ -0,0 +1,42 @@
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function migrate() {
console.log('Starting migration...');
const plans = await prisma.workoutPlan.findMany();
console.log(`Found ${plans.length} plans.`);
for (const plan of plans) {
if (plan.exercises) {
try {
const steps = JSON.parse(plan.exercises);
console.log(`Migrating plan ${plan.name} (${plan.id}) with ${steps.length} steps.`);
let order = 0;
for (const step of steps) {
await prisma.planExercise.create({
data: {
planId: plan.id,
exerciseId: step.exerciseId,
order: order++,
isWeighted: step.isWeighted || false
}
});
}
} catch (e) {
console.error(`Error parsing JSON for plan ${plan.id}:`, e);
}
}
}
console.log('Migration complete.');
}
migrate()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});