fitness: add workout schedule rotation with next-workout suggestion
All checks were successful
CI / update (push) Successful in 2m2s

Users can define a custom order of templates (e.g., Push → Pull → Legs).
Based on the last completed session, the next workout in rotation is
recommended via a prominent banner and the floating action button.

- New WorkoutSchedule MongoDB model (per-user template order)
- GET/PUT /api/fitness/schedule API endpoints
- Schedule editor modal with reorder and add/remove
- Action button starts next scheduled workout when schedule exists
This commit is contained in:
2026-03-21 10:53:42 +01:00
parent 2bede967c2
commit 6103bb75a0
4 changed files with 511 additions and 5 deletions

View File

@@ -0,0 +1,31 @@
import mongoose from 'mongoose';
export interface IWorkoutSchedule {
_id?: string;
userId: string;
templateOrder: string[]; // array of WorkoutTemplate _id strings in rotation order
createdAt?: Date;
updatedAt?: Date;
}
const WorkoutScheduleSchema = new mongoose.Schema(
{
userId: {
type: String,
required: true,
unique: true,
trim: true
},
templateOrder: {
type: [String],
default: []
}
},
{
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true }
}
);
export const WorkoutSchedule = mongoose.model<IWorkoutSchedule>('WorkoutSchedule', WorkoutScheduleSchema);

View File

@@ -0,0 +1,96 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { dbConnect } from '$utils/db';
import { WorkoutSchedule } from '$models/WorkoutSchedule';
import { WorkoutSession } from '$models/WorkoutSession';
import { WorkoutTemplate } from '$models/WorkoutTemplate';
import { requireAuth } from '$lib/server/middleware/auth';
// GET /api/fitness/schedule - Get the user's workout schedule and next workout
export const GET: RequestHandler = async ({ locals }) => {
const user = await requireAuth(locals);
try {
await dbConnect();
const schedule = await WorkoutSchedule.findOne({ userId: user.nickname });
if (!schedule || schedule.templateOrder.length === 0) {
return json({ schedule: null, nextTemplateId: null });
}
// Find the most recent session that used a template in the schedule
const lastSession = await WorkoutSession.findOne({
createdBy: user.nickname,
templateId: { $in: schedule.templateOrder }
}).sort({ startTime: -1 });
let nextTemplateId: string;
if (!lastSession?.templateId) {
// No previous session — start at the first template
nextTemplateId = schedule.templateOrder[0];
} else {
const lastId = lastSession.templateId.toString();
const idx = schedule.templateOrder.indexOf(lastId);
if (idx === -1) {
// Last session's template no longer in schedule — start at first
nextTemplateId = schedule.templateOrder[0];
} else {
// Next in rotation (wraps around)
nextTemplateId = schedule.templateOrder[(idx + 1) % schedule.templateOrder.length];
}
}
// Verify the template still exists
const templateExists = await WorkoutTemplate.exists({ _id: nextTemplateId });
if (!templateExists) {
nextTemplateId = schedule.templateOrder[0];
}
return json({
schedule: { templateOrder: schedule.templateOrder },
nextTemplateId
});
} catch (error) {
console.error('Error fetching workout schedule:', error);
return json({ error: 'Failed to fetch workout schedule' }, { status: 500 });
}
};
// PUT /api/fitness/schedule - Save the user's workout schedule (template order)
export const PUT: RequestHandler = async ({ request, locals }) => {
const user = await requireAuth(locals);
try {
await dbConnect();
const { templateOrder } = await request.json();
if (!Array.isArray(templateOrder)) {
return json({ error: 'templateOrder must be an array' }, { status: 400 });
}
// Validate all template IDs belong to this user
if (templateOrder.length > 0) {
const count = await WorkoutTemplate.countDocuments({
_id: { $in: templateOrder },
createdBy: user.nickname
});
if (count !== templateOrder.length) {
return json({ error: 'Some template IDs are invalid' }, { status: 400 });
}
}
const schedule = await WorkoutSchedule.findOneAndUpdate(
{ userId: user.nickname },
{ templateOrder },
{ upsert: true, new: true }
);
return json({ schedule: { templateOrder: schedule.templateOrder } });
} catch (error) {
console.error('Error saving workout schedule:', error);
return json({ error: 'Failed to save workout schedule' }, { status: 500 });
}
};

View File

@@ -1,8 +1,13 @@
import type { PageServerLoad } from './$types'; import type { PageServerLoad } from './$types';
export const load: PageServerLoad = async ({ fetch }) => { export const load: PageServerLoad = async ({ fetch }) => {
const res = await fetch('/api/fitness/templates'); const [templatesRes, scheduleRes] = await Promise.all([
fetch('/api/fitness/templates'),
fetch('/api/fitness/schedule')
]);
return { return {
templates: await res.json() templates: await templatesRes.json(),
schedule: await scheduleRes.json()
}; };
}; };

View File

@@ -1,7 +1,7 @@
<script> <script>
import { goto } from '$app/navigation'; import { goto } from '$app/navigation';
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { Plus, Trash2, Play, Pencil, X, Save } from 'lucide-svelte'; import { Plus, Trash2, Play, Pencil, X, Save, CalendarClock, GripVertical, ChevronUp, ChevronDown, ArrowRight } from 'lucide-svelte';
import { getWorkout } from '$lib/js/workout.svelte'; import { getWorkout } from '$lib/js/workout.svelte';
import { getWorkoutSync } from '$lib/js/workoutSync.svelte'; import { getWorkoutSync } from '$lib/js/workoutSync.svelte';
import { getExerciseById, getExerciseMetrics, METRIC_LABELS } from '$lib/data/exercises'; import { getExerciseById, getExerciseMetrics, METRIC_LABELS } from '$lib/data/exercises';
@@ -16,6 +16,16 @@
let templates = $state(data.templates?.templates ? [...data.templates.templates] : []); let templates = $state(data.templates?.templates ? [...data.templates.templates] : []);
let seeded = $state(false); let seeded = $state(false);
// Schedule state
/** @type {string[]} */
let scheduleOrder = $state(data.schedule?.schedule?.templateOrder ?? []);
/** @type {string | null} */
let nextTemplateId = $state(data.schedule?.nextTemplateId ?? null);
let showScheduleEditor = $state(false);
/** @type {string[]} */
let editorScheduleOrder = $state([]);
let scheduleSaving = $state(false);
// Template detail modal // Template detail modal
/** @type {any} */ /** @type {any} */
let selectedTemplate = $state(null); let selectedTemplate = $state(null);
@@ -30,6 +40,10 @@
let editorPicker = $state(false); let editorPicker = $state(false);
let editorSaving = $state(false); let editorSaving = $state(false);
/** @type {any} */
let nextTemplate = $derived(nextTemplateId ? templates.find((t) => t._id === nextTemplateId) : null);
let hasSchedule = $derived(scheduleOrder.length > 0);
onMount(() => { onMount(() => {
workout.restore(); workout.restore();
@@ -74,6 +88,11 @@
goto('/fitness/workout/active'); goto('/fitness/workout/active');
} }
async function startNextScheduled() {
if (!nextTemplate) return;
await startFromTemplate(nextTemplate);
}
function openCreateTemplate() { function openCreateTemplate() {
editingTemplate = null; editingTemplate = null;
editorName = ''; editorName = '';
@@ -190,12 +209,101 @@
const res = await fetch(`/api/fitness/templates/${template._id}`, { method: 'DELETE' }); const res = await fetch(`/api/fitness/templates/${template._id}`, { method: 'DELETE' });
if (res.ok) { if (res.ok) {
templates = templates.filter((t) => t._id !== template._id); templates = templates.filter((t) => t._id !== template._id);
// Also remove from schedule if present
if (scheduleOrder.includes(template._id)) {
scheduleOrder = scheduleOrder.filter((id) => id !== template._id);
saveSchedule(scheduleOrder);
}
} }
} catch {} } catch {}
} }
// Schedule editor functions
function openScheduleEditor() {
editorScheduleOrder = [...scheduleOrder];
showScheduleEditor = true;
}
function closeScheduleEditor() {
showScheduleEditor = false;
}
/** @param {number} idx @param {number} dir */
function moveScheduleItem(idx, dir) {
const newIdx = idx + dir;
if (newIdx < 0 || newIdx >= editorScheduleOrder.length) return;
const copy = [...editorScheduleOrder];
[copy[idx], copy[newIdx]] = [copy[newIdx], copy[idx]];
editorScheduleOrder = copy;
}
/** @param {string} templateId */
function toggleScheduleTemplate(templateId) {
if (editorScheduleOrder.includes(templateId)) {
editorScheduleOrder = editorScheduleOrder.filter((id) => id !== templateId);
} else {
editorScheduleOrder = [...editorScheduleOrder, templateId];
}
}
/** @param {string[]} order */
async function saveSchedule(order) {
try {
const res = await fetch('/api/fitness/schedule', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ templateOrder: order })
});
if (res.ok) {
scheduleOrder = order;
// Refresh next template
const schedRes = await fetch('/api/fitness/schedule');
const schedData = await schedRes.json();
nextTemplateId = schedData.nextTemplateId ?? null;
}
} catch {}
}
async function saveAndCloseSchedule() {
scheduleSaving = true;
await saveSchedule(editorScheduleOrder);
scheduleSaving = false;
showScheduleEditor = false;
}
/** @param {string} id */
function getTemplateName(id) {
return templates.find((t) => t._id === id)?.name ?? 'Unknown';
}
</script> </script>
<div class="template-view"> <div class="template-view">
{#if hasSchedule && nextTemplate}
<section class="next-workout">
<div class="next-label">
<CalendarClock size={16} />
<span>Next in schedule</span>
</div>
<button class="next-workout-btn" onclick={startNextScheduled}>
<div class="next-info">
<span class="next-name">{nextTemplate.name}</span>
<span class="next-exercises">{nextTemplate.exercises.length} exercise{nextTemplate.exercises.length !== 1 ? 's' : ''}</span>
</div>
<div class="next-go">
<Play size={18} />
</div>
</button>
<div class="schedule-preview">
{#each scheduleOrder as id, i}
<span class="schedule-dot" class:active={id === nextTemplateId}>{getTemplateName(id)}</span>
{#if i < scheduleOrder.length - 1}
<ArrowRight size={12} />
{/if}
{/each}
</div>
</section>
{/if}
<section class="quick-start"> <section class="quick-start">
<button class="start-empty-btn" onclick={startEmpty}> <button class="start-empty-btn" onclick={startEmpty}>
START AN EMPTY WORKOUT START AN EMPTY WORKOUT
@@ -203,7 +311,13 @@
</section> </section>
<section class="templates-section"> <section class="templates-section">
<div class="templates-header">
<h2>Templates</h2> <h2>Templates</h2>
<button class="schedule-btn" onclick={openScheduleEditor} aria-label="Edit workout schedule">
<CalendarClock size={16} />
Schedule
</button>
</div>
{#if templates.length > 0} {#if templates.length > 0}
<p class="template-count">My Templates ({templates.length})</p> <p class="template-count">My Templates ({templates.length})</p>
<div class="template-grid"> <div class="template-grid">
@@ -328,9 +442,71 @@
{/if} {/if}
{/if} {/if}
<!-- Schedule Editor Modal -->
{#if showScheduleEditor}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="modal-overlay" onkeydown={(e) => e.key === 'Escape' && closeScheduleEditor()}>
<!-- svelte-ignore a11y_click_events_have_key_events -->
<div class="modal-backdrop" onclick={closeScheduleEditor}></div>
<div class="modal-panel editor-panel">
<div class="modal-header">
<h2>Workout Schedule</h2>
<button class="close-btn" onclick={closeScheduleEditor} aria-label="Close"><X size={20} /></button>
</div>
<div class="modal-body">
<p class="schedule-hint">Select templates and arrange their order. After completing a workout, the next one in the rotation will be suggested.</p>
{#if editorScheduleOrder.length > 0}
<div class="schedule-order">
{#each editorScheduleOrder as id, idx (id)}
<div class="schedule-item">
<span class="schedule-pos">{idx + 1}</span>
<span class="schedule-item-name">{getTemplateName(id)}</span>
<div class="schedule-item-actions">
<button disabled={idx === 0} onclick={() => moveScheduleItem(idx, -1)} aria-label="Move up">
<ChevronUp size={16} />
</button>
<button disabled={idx === editorScheduleOrder.length - 1} onclick={() => moveScheduleItem(idx, 1)} aria-label="Move down">
<ChevronDown size={16} />
</button>
<button onclick={() => toggleScheduleTemplate(id)} aria-label="Remove from schedule" class="schedule-remove">
<X size={16} />
</button>
</div>
</div>
{/each}
</div>
{/if}
<div class="schedule-available">
<p class="schedule-available-label">Available templates</p>
{#each templates.filter((t) => !editorScheduleOrder.includes(t._id)) as template (template._id)}
<button class="schedule-add-item" onclick={() => toggleScheduleTemplate(template._id)}>
<Plus size={14} />
<span>{template.name}</span>
</button>
{/each}
{#if templates.filter((t) => !editorScheduleOrder.includes(t._id)).length === 0}
<p class="schedule-all-added">All templates are in the schedule</p>
{/if}
</div>
</div>
<div class="modal-actions">
<button class="modal-start" onclick={saveAndCloseSchedule} disabled={scheduleSaving}>
<Save size={16} /> {scheduleSaving ? 'Saving…' : 'Save Schedule'}
</button>
</div>
</div>
</div>
{/if}
{#if !workout.active} {#if !workout.active}
{#if hasSchedule && nextTemplate}
<AddActionButton onclick={startNextScheduled} ariaLabel="Start next scheduled workout: {nextTemplate.name}" />
{:else}
<AddActionButton onclick={openCreateTemplate} ariaLabel="Create template" /> <AddActionButton onclick={openCreateTemplate} ariaLabel="Create template" />
{/if} {/if}
{/if}
<style> <style>
/* Template View */ /* Template View */
@@ -339,6 +515,81 @@
flex-direction: column; flex-direction: column;
gap: 1.5rem; gap: 1.5rem;
} }
/* Next Workout Banner */
.next-workout {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.next-label {
display: flex;
align-items: center;
gap: 0.4rem;
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--color-text-secondary);
}
.next-workout-btn {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1rem;
background: var(--color-primary);
color: white;
border: none;
border-radius: 10px;
cursor: pointer;
text-align: left;
transition: opacity 150ms ease;
}
.next-workout-btn:hover {
opacity: 0.9;
}
.next-info {
display: flex;
flex-direction: column;
gap: 0.15rem;
}
.next-name {
font-weight: 700;
font-size: 1rem;
}
.next-exercises {
font-size: 0.8rem;
opacity: 0.85;
}
.next-go {
display: flex;
align-items: center;
justify-content: center;
width: 2.5rem;
height: 2.5rem;
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
}
.schedule-preview {
display: flex;
align-items: center;
gap: 0.35rem;
flex-wrap: wrap;
font-size: 0.7rem;
color: var(--color-text-secondary);
}
.schedule-dot {
padding: 0.15rem 0.4rem;
background: var(--color-bg-elevated);
border-radius: 4px;
white-space: nowrap;
}
.schedule-dot.active {
background: var(--color-primary);
color: white;
font-weight: 600;
}
.quick-start { .quick-start {
text-align: center; text-align: center;
} }
@@ -357,10 +608,32 @@
.start-empty-btn:hover { .start-empty-btn:hover {
opacity: 0.9; opacity: 0.9;
} }
.templates-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.templates-section h2 { .templates-section h2 {
margin: 0; margin: 0;
font-size: 1.2rem; font-size: 1.2rem;
} }
.schedule-btn {
display: flex;
align-items: center;
gap: 0.3rem;
padding: 0.35rem 0.65rem;
background: var(--color-bg-elevated);
border: 1px solid var(--color-border);
border-radius: 6px;
color: var(--color-text-secondary);
font-size: 0.75rem;
font-weight: 600;
cursor: pointer;
}
.schedule-btn:hover {
border-color: var(--color-primary);
color: var(--color-primary);
}
.template-count { .template-count {
font-size: 0.8rem; font-size: 0.8rem;
color: var(--color-text-secondary); color: var(--color-text-secondary);
@@ -632,4 +905,105 @@
color: var(--color-primary); color: var(--color-primary);
} }
/* Schedule Editor */
.schedule-hint {
font-size: 0.8rem;
color: var(--color-text-secondary);
margin: 0 0 1rem;
line-height: 1.4;
}
.schedule-order {
display: flex;
flex-direction: column;
gap: 0.35rem;
margin-bottom: 1rem;
}
.schedule-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 0.65rem;
background: var(--color-bg-elevated);
border: 1px solid var(--color-border);
border-radius: 8px;
}
.schedule-pos {
width: 1.3rem;
height: 1.3rem;
display: flex;
align-items: center;
justify-content: center;
background: var(--color-primary);
color: white;
border-radius: 50%;
font-size: 0.7rem;
font-weight: 700;
flex-shrink: 0;
}
.schedule-item-name {
flex: 1;
font-size: 0.85rem;
font-weight: 600;
}
.schedule-item-actions {
display: flex;
gap: 0.15rem;
}
.schedule-item-actions button {
background: none;
border: none;
color: var(--color-text-secondary);
cursor: pointer;
padding: 0.2rem;
border-radius: 4px;
}
.schedule-item-actions button:hover:not(:disabled) {
color: var(--color-primary);
}
.schedule-item-actions button:disabled {
opacity: 0.3;
cursor: not-allowed;
}
.schedule-remove:hover:not(:disabled) {
color: var(--nord11) !important;
}
.schedule-available {
border-top: 1px solid var(--color-border);
padding-top: 0.75rem;
}
.schedule-available-label {
font-size: 0.75rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--color-text-secondary);
margin: 0 0 0.5rem;
}
.schedule-add-item {
display: flex;
align-items: center;
gap: 0.4rem;
width: 100%;
padding: 0.5rem 0.65rem;
background: transparent;
border: 1px dashed var(--color-border);
border-radius: 8px;
color: var(--color-text-secondary);
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
margin-bottom: 0.35rem;
text-align: left;
}
.schedule-add-item:hover {
border-color: var(--color-primary);
color: var(--color-primary);
}
.schedule-all-added {
font-size: 0.8rem;
color: var(--color-text-secondary);
text-align: center;
padding: 0.5rem 0;
margin: 0;
}
</style> </style>