Default Exercises Set for new User

This commit is contained in:
AG
2025-12-15 20:02:39 +02:00
parent 003c045621
commit 170e32d36c
7 changed files with 196 additions and 2 deletions

View File

@@ -1,6 +1,9 @@
import prisma from '../lib/prisma';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import fs from 'fs';
import path from 'path';
import dotenv from 'dotenv';
const JWT_SECRET = process.env.JWT_SECRET || 'secret';
@@ -64,6 +67,74 @@ export class AuthService {
include: { profile: true }
});
// Seed default exercises
try {
// Ensure env is loaded (in case server didn't restart)
if (!process.env.DEFAULT_EXERCISES_CSV_PATH) {
dotenv.config({ path: path.resolve(process.cwd(), '.env'), override: true });
if (!process.env.DEFAULT_EXERCISES_CSV_PATH) {
// Try root if CWD is server
dotenv.config({ path: path.resolve(process.cwd(), '../.env'), override: true });
}
}
const csvPath = process.env.DEFAULT_EXERCISES_CSV_PATH;
if (csvPath) {
// ... logic continues
let resolvedPath = path.resolve(process.cwd(), csvPath);
// Try to handle if resolvedPath doesn't exist but relative to root does (if CWD is server)
if (!fs.existsSync(resolvedPath) && !path.isAbsolute(csvPath)) {
const altPath = path.resolve(process.cwd(), '..', csvPath);
if (fs.existsSync(altPath)) {
resolvedPath = altPath;
}
}
if (fs.existsSync(resolvedPath)) {
const content = fs.readFileSync(resolvedPath, 'utf-8');
const lines = content.split(/\r?\n/).filter(l => l.trim().length > 0);
if (lines.length > 1) {
const headers = lines[0].split(',').map(h => h.trim());
const exercisesToCreate = [];
for (let i = 1; i < lines.length; i++) {
const cols = lines[i].split(',').map(c => c.trim());
if (cols.length < headers.length) continue;
const row: any = {};
headers.forEach((h, idx) => row[h] = cols[idx]);
if (row.name && row.type) {
exercisesToCreate.push({
userId: user.id,
name: row.name,
type: row.type,
bodyWeightPercentage: row.bodyWeightPercentage ? parseFloat(row.bodyWeightPercentage) : 0,
isUnilateral: row.isUnilateral === 'true',
isArchived: false
});
}
}
if (exercisesToCreate.length > 0) {
await prisma.exercise.createMany({
data: exercisesToCreate
});
}
}
} else {
console.warn(`[AuthService] Default exercises CSV configured but not found at: ${resolvedPath}`);
}
}
} catch (error) {
try { fs.appendFileSync(path.join(process.cwd(), 'auth_debug_custom.log'), `[${new Date().toISOString()}] ERROR: ${error}\n`); } catch (e) { }
console.error('[AuthService] Failed to seed default exercises:', error);
// Non-blocking error
}
const token = jwt.sign({ userId: user.id, role: user.role }, JWT_SECRET);
const { password: _, ...userSafe } = user;