Repository navigation
Expand file tree
/
Copy pathserver.ts
More file actions
505 lines (431 loc) · 19.7 KB
/
Copy pathserver.ts
File metadata and controls
505 lines (431 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
import express from "express";
import { createServer as createViteServer } from "vite";
import Database from "better-sqlite3";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const db = new Database("workout.db");
// Initialize database
db.exec(`
CREATE TABLE IF NOT EXISTS workouts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
description TEXT
);
CREATE TABLE IF NOT EXISTS exercises (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workout_id INTEGER,
name TEXT NOT NULL,
reps TEXT,
notes TEXT,
target_sets INTEGER DEFAULT 3,
order_index INTEGER,
is_warmup INTEGER DEFAULT 0,
is_timed INTEGER DEFAULT 0,
duration_seconds INTEGER DEFAULT 0,
weight TEXT,
FOREIGN KEY (workout_id) REFERENCES workouts(id)
);
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
workout_id INTEGER,
date TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
status TEXT DEFAULT 'active', -- active, completed
duration INTEGER DEFAULT 0, -- in seconds
FOREIGN KEY (workout_id) REFERENCES workouts(id)
);
CREATE TABLE IF NOT EXISTS session_progress (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id INTEGER,
exercise_id INTEGER,
completed_sets INTEGER DEFAULT 0,
weight TEXT,
FOREIGN KEY (session_id) REFERENCES sessions(id),
FOREIGN KEY (exercise_id) REFERENCES exercises(id)
);
CREATE TABLE IF NOT EXISTS presets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
reps TEXT,
notes TEXT,
target_sets INTEGER DEFAULT 3,
is_warmup INTEGER DEFAULT 0,
is_timed INTEGER DEFAULT 0,
duration_seconds INTEGER DEFAULT 0,
weight TEXT
);
`);
// Migrations
try {
db.exec("ALTER TABLE sessions ADD COLUMN duration INTEGER DEFAULT 0");
} catch (e) {}
try {
db.exec("ALTER TABLE exercises ADD COLUMN is_warmup INTEGER DEFAULT 0");
db.exec("ALTER TABLE presets ADD COLUMN is_warmup INTEGER DEFAULT 0");
} catch (e) {}
try {
db.exec("ALTER TABLE exercises ADD COLUMN weight TEXT");
db.exec("ALTER TABLE presets ADD COLUMN weight TEXT");
db.exec("ALTER TABLE session_progress ADD COLUMN weight TEXT");
} catch (e) {}
try {
db.exec("ALTER TABLE exercises ADD COLUMN is_timed INTEGER DEFAULT 0");
db.exec("ALTER TABLE exercises ADD COLUMN duration_seconds INTEGER DEFAULT 0");
db.exec("ALTER TABLE presets ADD COLUMN is_timed INTEGER DEFAULT 0");
db.exec("ALTER TABLE presets ADD COLUMN duration_seconds INTEGER DEFAULT 0");
} catch (e) {}
// Seed initial data if empty
const workoutCount = db.prepare("SELECT count(*) as count FROM workouts").get() as { count: number };
if (workoutCount.count === 0) {
const insertWorkout = db.prepare("INSERT INTO workouts (name, description) VALUES (?, ?)");
const insertExercise = db.prepare("INSERT INTO exercises (workout_id, name, reps, notes, target_sets, order_index, is_warmup, is_timed, duration_seconds) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
const insertPreset = db.prepare("INSERT INTO presets (name, reps, notes, target_sets, is_warmup, is_timed, duration_seconds) VALUES (?, ?, ?, ?, ?, ?, ?)");
const strengthWorkoutId = insertWorkout.run("Strength Workout (Modified)", "Perform 3–4 rounds instead of 5 while rehabbing.").lastInsertRowid;
const strengthExercises = [
["Kettlebell overhead press", "10 reps", "No Achilles load — keep as is.", 4, 0, 0, 0, 0],
["Push-ups", "10–15 reps", "Keep as is.", 4, 1, 0, 0, 0],
["Hex bar deadlift", "8–10 reps", "Keep moderate weight. Focus on slow control, no explosive push off.", 4, 2, 0, 0, 0],
["Goblet squat", "8–10 reps", "Slow tempo. If it irritates the Achilles, reduce depth slightly.", 4, 3, 0, 0, 0],
["Suitcase carries", "30–40s each side", "28 kg. Trains core and grip without stressing Achilles.", 4, 4, 0, 1, 40],
];
strengthExercises.forEach((ex, i) => {
insertExercise.run(strengthWorkoutId, ...ex);
// Also add to presets for convenience
insertPreset.run(ex[0], ex[1], ex[2], ex[3], ex[5], ex[6], ex[7]);
});
const achillesWorkoutId = insertWorkout.run("Achilles Strength Block", "10 minutes. Do this after the workout.").lastInsertRowid;
const achillesExercises = [
["Slow calf raises", "3 x 15", "3s up, 1s hold, 4s down. Do not drop below floor level.", 3, 0, 0, 0, 0],
["Bent-knee calf raises (soleus)", "3 x 12", "Protects the Achilles during walking.", 3, 1, 0, 0, 0],
["Posterior tibialis band work", "3 x 15 each foot", "Resistance band, pull foot inward slowly.", 3, 2, 0, 0, 0],
["Short-foot exercise", "10 x 10s holds", "Raise arch slightly without curling toes.", 1, 3, 0, 0, 0],
];
achillesExercises.forEach((ex, i) => {
insertExercise.run(achillesWorkoutId, ...ex);
insertPreset.run(ex[0], ex[1], ex[2], ex[3], ex[5], ex[6], ex[7]);
});
const warmupExercises = [
["Rowing machine", "5 min", "Focus on steady pace.", 1, 0, 1, 1, 300],
["Kettlebell halos (12 kg)", "2 x 10", "Keep core tight, move KB around head.", 2, 1, 1, 0, 0],
["Isometric farmer carries (28 kg)", "2-3 x 30s each side", "Stand tall, do not lean.", 3, 2, 1, 1, 30],
["Isometric calf holds", "5 x 30s", "Hold at the top of a calf raise.", 5, 3, 1, 1, 30],
];
warmupExercises.forEach((ex) => {
insertPreset.run(ex[0], ex[1], ex[2], ex[3], ex[5], ex[6], ex[7]);
});
}
// Ensure Achilles Strength Block has exercises (repair for existing DBs)
const achillesWorkout = db.prepare("SELECT id FROM workouts WHERE name = 'Achilles Strength Block'").get() as any;
if (achillesWorkout) {
const exerciseCount = db.prepare("SELECT count(*) as count FROM exercises WHERE workout_id = ?").get(achillesWorkout.id) as { count: number };
if (exerciseCount.count === 0) {
const insertExercise = db.prepare("INSERT INTO exercises (workout_id, name, reps, notes, target_sets, order_index, is_warmup, is_timed, duration_seconds) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
const achillesExercises = [
["Slow calf raises", "3 x 15", "3s up, 1s hold, 4s down. Do not drop below floor level.", 3, 0, 0, 0, 0],
["Bent-knee calf raises (soleus)", "3 x 12", "Protects the Achilles during walking.", 3, 1, 0, 0, 0],
["Posterior tibialis band work", "3 x 15 each foot", "Resistance band, pull foot inward slowly.", 3, 2, 0, 0, 0],
["Short-foot exercise", "10 x 10s holds", "Raise arch slightly without curling toes.", 1, 3, 0, 0, 0],
];
achillesExercises.forEach((ex) => {
insertExercise.run(achillesWorkout.id, ...ex);
});
}
}
// Ensure warmup presets exist even if DB was already seeded
const warmupPresetCount = db.prepare("SELECT count(*) as count FROM presets WHERE is_warmup = 1").get() as { count: number };
if (warmupPresetCount.count === 0) {
const insertPreset = db.prepare("INSERT INTO presets (name, reps, notes, target_sets, is_warmup, is_timed, duration_seconds) VALUES (?, ?, ?, ?, ?, ?, ?)");
const warmupExercises = [
["Rowing machine", "5 min", "Focus on steady pace.", 1, 0, 1, 1, 300],
["Kettlebell halos (12 kg)", "2 x 10", "Keep core tight, move KB around head.", 2, 1, 1, 0, 0],
["Isometric farmer carries (28 kg)", "2-3 x 30s each side", "Stand tall, do not lean.", 3, 2, 1, 1, 30],
["Isometric calf holds", "5 x 30s", "Hold at the top of a calf raise.", 5, 3, 1, 1, 30],
];
warmupExercises.forEach((ex) => {
insertPreset.run(ex[0], ex[1], ex[2], ex[3], ex[5], ex[6], ex[7]);
});
}
// Update existing "Farmer's Carry" presets to be timed if they aren't already
try {
db.prepare(`
UPDATE presets
SET is_timed = 1, duration_seconds = 30
WHERE (name LIKE '%farmer%' OR name LIKE '%carry%')
AND is_timed = 0
`).run();
db.prepare(`
UPDATE exercises
SET is_timed = 1, duration_seconds = 30
WHERE (name LIKE '%farmer%' OR name LIKE '%carry%')
AND is_timed = 0
`).run();
} catch (e) {
console.error("Failed to update carry presets:", e);
}
async function startServer() {
const app = express();
app.use(express.json());
// API Routes
app.get("/api/workouts", (req, res) => {
const workouts = db.prepare("SELECT * FROM workouts").all();
res.json(workouts);
});
app.get("/api/workouts/:id/exercises", (req, res) => {
const exercises = db.prepare("SELECT * FROM exercises WHERE workout_id = ? ORDER BY order_index").all(req.params.id);
res.json(exercises);
});
app.get("/api/sessions/active", (req, res) => {
const session = db.prepare(`
SELECT s.*, w.name as workout_name
FROM sessions s
JOIN workouts w ON s.workout_id = w.id
WHERE s.status = 'active'
ORDER BY s.date DESC LIMIT 1
`).get();
if (!session) return res.json(null);
const progress = db.prepare(`
SELECT sp.*, e.name, e.reps, e.notes, e.target_sets, e.is_warmup, e.is_timed, e.duration_seconds
FROM session_progress sp
JOIN exercises e ON sp.exercise_id = e.id
WHERE sp.session_id = ?
ORDER BY e.order_index
`).all((session as any).id);
// If weight is null in session_progress, fallback to exercise default weight
const progressWithWeights = progress.map((p: any) => {
if (p.weight === null) {
const exercise = db.prepare("SELECT weight FROM exercises WHERE id = ?").get(p.exercise_id) as any;
return { ...p, weight: exercise?.weight || "" };
}
return p;
});
res.json({ ...session, exercises: progressWithWeights });
});
app.post("/api/sessions/start", (req, res) => {
const { workoutId } = req.body;
const now = new Date().toISOString();
// Close any existing active sessions
db.prepare("UPDATE sessions SET status = 'completed' WHERE status = 'active'").run();
const sessionResult = db.prepare("INSERT INTO sessions (workout_id, date) VALUES (?, ?)").run(workoutId, now);
const sessionId = sessionResult.lastInsertRowid;
const exercises = db.prepare("SELECT id, target_sets, weight FROM exercises WHERE workout_id = ?").all(workoutId) as any[];
const insertProgress = db.prepare("INSERT INTO session_progress (session_id, exercise_id, completed_sets, weight) VALUES (?, ?, 0, ?)");
exercises.forEach(ex => insertProgress.run(sessionId, ex.id, ex.weight));
res.json({ id: sessionId });
});
app.post("/api/sessions/:id/increment", (req, res) => {
const { exerciseId } = req.body;
db.prepare(`
UPDATE session_progress
SET completed_sets = completed_sets + 1
WHERE session_id = ? AND exercise_id = ?
`).run(req.params.id, exerciseId);
res.json({ success: true });
});
app.post("/api/sessions/:id/decrement", (req, res) => {
const { exerciseId } = req.body;
db.prepare(`
UPDATE session_progress
SET completed_sets = MAX(0, completed_sets - 1)
WHERE session_id = ? AND exercise_id = ?
`).run(req.params.id, exerciseId);
res.json({ success: true });
});
app.post("/api/sessions/:id/update-weight", (req, res) => {
const { exerciseId, weight } = req.body;
db.prepare(`
UPDATE session_progress
SET weight = ?
WHERE session_id = ? AND exercise_id = ?
`).run(weight, req.params.id, exerciseId);
res.json({ success: true });
});
app.get("/api/presets", (req, res) => {
const presets = db.prepare("SELECT * FROM presets ORDER BY name").all();
res.json(presets);
});
app.post("/api/presets", (req, res) => {
const { name, reps, notes, target_sets, weight, is_timed, duration_seconds } = req.body;
const result = db.prepare("INSERT INTO presets (name, reps, notes, target_sets, weight, is_timed, duration_seconds) VALUES (?, ?, ?, ?, ?, ?, ?)").run(name, reps, notes, target_sets, weight, is_timed || 0, duration_seconds || 0);
res.json({ id: result.lastInsertRowid });
});
app.post("/api/sessions/:id/add-exercise", (req, res) => {
const { name, reps, notes, target_sets, weight, is_timed, duration_seconds } = req.body;
const sessionId = req.params.id;
// We need to create a "ghost" exercise or just add to session_progress with a new exercise entry
// For simplicity, let's add it to the exercises table with a null workout_id or a special "custom" workout_id
// But better: just create a new exercise record for this specific session if it's custom
const exerciseResult = db.prepare("INSERT INTO exercises (name, reps, notes, target_sets, weight, is_timed, duration_seconds) VALUES (?, ?, ?, ?, ?, ?, ?)").run(name, reps, notes, target_sets, weight, is_timed || 0, duration_seconds || 0);
const exerciseId = exerciseResult.lastInsertRowid;
db.prepare("INSERT INTO session_progress (session_id, exercise_id, completed_sets, weight) VALUES (?, ?, 0, ?)").run(sessionId, exerciseId, weight);
res.json({ success: true });
});
app.post("/api/sessions/:id/complete", (req, res) => {
const { duration } = req.body;
db.prepare("UPDATE sessions SET status = 'completed', duration = ? WHERE id = ?").run(duration || 0, req.params.id);
res.json({ success: true });
});
app.delete("/api/sessions/:id", (req, res) => {
const sessionId = req.params.id;
db.transaction(() => {
// Delete session progress first
db.prepare("DELETE FROM session_progress WHERE session_id = ?").run(sessionId);
// Delete the session itself
db.prepare("DELETE FROM sessions WHERE id = ?").run(sessionId);
})();
res.json({ success: true });
});
app.get("/api/analytics/volume", (req, res) => {
const data = db.prepare(`
SELECT date(s.date) as day, SUM(sp.completed_sets) as total_sets
FROM sessions s
JOIN session_progress sp ON s.id = sp.session_id
WHERE s.status = 'completed'
GROUP BY day
HAVING total_sets > 0
ORDER BY day ASC
LIMIT 30
`).all();
res.json(data);
});
app.get("/api/history", (req, res) => {
const sessions = db.prepare(`
SELECT s.*, w.name as workout_name
FROM sessions s
JOIN workouts w ON s.workout_id = w.id
WHERE s.status = 'completed'
AND EXISTS (
SELECT 1 FROM session_progress sp
WHERE sp.session_id = s.id AND sp.completed_sets > 0
)
ORDER BY s.date DESC
LIMIT 20
`).all();
const history = sessions.map((session: any) => {
const exercises = db.prepare(`
SELECT sp.*, e.name, e.reps, e.notes, e.is_warmup
FROM session_progress sp
JOIN exercises e ON sp.exercise_id = e.id
WHERE sp.session_id = ?
`).all(session.id);
return { ...session, exercises };
});
res.json(history);
});
app.post("/api/exercises/:id/reorder", (req, res) => {
const { direction } = req.body; // 'up' or 'down'
const exerciseId = req.params.id;
const current = db.prepare("SELECT workout_id, order_index FROM exercises WHERE id = ?").get(exerciseId) as any;
if (!current) return res.status(404).json({ error: "Exercise not found" });
const swapWith = db.prepare(`
SELECT id, order_index
FROM exercises
WHERE workout_id = ? AND order_index ${direction === 'up' ? '<' : '>'} ?
ORDER BY order_index ${direction === 'up' ? 'DESC' : 'ASC'}
LIMIT 1
`).get(current.workout_id, current.order_index) as any;
if (swapWith) {
const update = db.prepare("UPDATE exercises SET order_index = ? WHERE id = ?");
update.run(swapWith.order_index, exerciseId);
update.run(current.order_index, swapWith.id);
}
res.json({ success: true });
});
app.post("/api/sessions/:id/add-warmup", (req, res) => {
const sessionId = req.params.id;
const warmupPresets = db.prepare("SELECT * FROM presets WHERE is_warmup = 1").all() as any[];
const insertExercise = db.prepare(`
INSERT INTO exercises (workout_id, name, reps, notes, target_sets, order_index, is_warmup, is_timed, duration_seconds)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const insertProgress = db.prepare("INSERT INTO session_progress (session_id, exercise_id, completed_sets) VALUES (?, ?, 0)");
db.transaction(() => {
warmupPresets.forEach((preset, index) => {
// Use workout_id = NULL to avoid polluting templates
// Use negative order_index to put at top
const result = insertExercise.run(null, preset.name, preset.reps, preset.notes, preset.target_sets, -100 + index, 1, preset.is_timed, preset.duration_seconds);
insertProgress.run(sessionId, result.lastInsertRowid);
});
})();
res.json({ success: true });
});
app.post("/api/sessions/start-warmup", (req, res) => {
const now = new Date().toISOString();
// Close any existing active sessions
db.prepare("UPDATE sessions SET status = 'completed' WHERE status = 'active'").run();
// Find or create "Warmup Routine" workout
let workout = db.prepare("SELECT id FROM workouts WHERE name = 'Warmup Routine'").get() as any;
if (!workout) {
const result = db.prepare("INSERT INTO workouts (name, description) VALUES (?, ?)").run("Warmup Routine", "Standard daily warmup");
workout = { id: result.lastInsertRowid };
// Add exercises to this new workout template
const warmupPresets = db.prepare("SELECT * FROM presets WHERE is_warmup = 1").all() as any[];
const insertExercise = db.prepare("INSERT INTO exercises (workout_id, name, reps, notes, target_sets, order_index, is_warmup, is_timed, duration_seconds) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
warmupPresets.forEach((p, i) => {
insertExercise.run(workout.id, p.name, p.reps, p.notes, p.target_sets, i, 1, p.is_timed, p.duration_seconds);
});
}
const sessionResult = db.prepare("INSERT INTO sessions (workout_id, date) VALUES (?, ?)").run(workout.id, now);
const sessionId = sessionResult.lastInsertRowid;
// Copy exercises from the workout template to session progress
const exercises = db.prepare("SELECT id, target_sets FROM exercises WHERE workout_id = ?").all(workout.id) as any[];
const insertProgress = db.prepare("INSERT INTO session_progress (session_id, exercise_id, completed_sets) VALUES (?, ?, 0)");
exercises.forEach(ex => insertProgress.run(sessionId, ex.id));
res.json({ id: sessionId });
});
app.post("/api/sessions/:id/reorder-all", (req, res) => {
const { exerciseIds } = req.body; // Array of exercise IDs in new order
const update = db.prepare("UPDATE exercises SET order_index = ? WHERE id = ?");
const transaction = db.transaction((ids) => {
ids.forEach((id: number, index: number) => {
update.run(index, id);
});
});
transaction(exerciseIds);
res.json({ success: true });
});
app.get("/manifest.json", (req, res) => {
res.json({
"name": "Achilles Rehab & Strength Tracker",
"short_name": "Achilles",
"description": "Workout tracker for rehab.",
"start_url": "/",
"display": "standalone",
"background_color": "#09090b",
"theme_color": "#10b981",
"icons": [
{
"src": "https://picsum.photos/seed/workout/192/192",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "https://picsum.photos/seed/workout/512/512",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
]
});
});
app.get("/sw.js", (req, res) => {
res.sendFile(path.resolve(__dirname, "sw.js"));
});
// Vite middleware for development
if (process.env.NODE_ENV !== "production") {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: "spa",
});
app.use(vite.middlewares);
} else {
app.use(express.static("dist"));
app.get("*", (req, res) => res.sendFile(path.resolve(__dirname, "dist", "index.html")));
}
const PORT = 3000;
app.listen(PORT, "0.0.0.0", () => {
console.log(`Server running on http://localhost:${PORT}`);
});
}
startServer();