Record completed training sessions, credit them, and add session-count goals
A driver completing the practice timer, "Jämna varv", or "Stegträning" now gets a permanent history entry instead of the outcome only existing as a one-off notification - visible on both their mobile profile and the admin Training page, so progress over past sessions is actually reviewable. Each completion earns a prominent emoji-badged credit. The completion is verified server-side against the driver's real recorded laps before being saved, reusing the same progress builders live tracking already uses - the client can only ask for a completion to be checked and recorded, never supply the outcome itself, so a driver can't fabricate a completed session (and the reward tied to it) any more than they could fabricate a lap time. Both per-driver and club-wide goals can now target "complete N sessions of one exercise kind" as an alternative to "N laps", sharing the existing reward/claim mechanism and forms. Fixes a real bug found while building this: a pre-existing two-argument wrapper around getTrainingGoalProgress in app.js silently dropped the new third argument, so every sessions-metric goal displayed 0 progress regardless of how many sessions were actually completed. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bed0dfd9f2
commit
1c4a06b69e
14 files changed
+800
-52
No files matched your search
+122
-8
@@ -27,7 +27,16 @@ const messages = {
|
||||
consistency: "Jämnhet senaste 30",
|
||||
nextLevel: "Nästa nivå",
|
||||
reachLaps: "Nå {laps} varv",
|
||||
reachSessions: "Genomför {count} pass",
|
||||
lapsRemaining: "{laps} varv kvar",
|
||||
timerSessionTitle: "Träningspass",
|
||||
exerciseHistoryTitle: "Träningshistorik",
|
||||
exerciseHistoryHint: "Genomförda träningspass - jämna varv, stegträning och vanliga pass - för att se utvecklingen över tid.",
|
||||
exerciseHistoryEmpty: "Inga genomförda träningspass ännu.",
|
||||
exerciseHistoryEvenLaps: "Serie på {streak} varv i mål {lap}",
|
||||
exerciseHistoryStepTraining: "{steps} steg, {laps} varv",
|
||||
exerciseHistoryTimer: "{laps} varv, snitt {lap}",
|
||||
exerciseSessionsCredit: "Du har genomfört {count} träningspass idag - snyggt jobbat!",
|
||||
plan: "Dagens träningspass",
|
||||
timerSetup: "Ställ in passet",
|
||||
pushMinutes: "Maxfokus (min)",
|
||||
@@ -184,7 +193,16 @@ const messages = {
|
||||
consistency: "Latest 30 consistency",
|
||||
nextLevel: "Next level",
|
||||
reachLaps: "Reach {laps} laps",
|
||||
reachSessions: "Complete {count} sessions",
|
||||
lapsRemaining: "{laps} laps remaining",
|
||||
timerSessionTitle: "Practice session",
|
||||
exerciseHistoryTitle: "Training history",
|
||||
exerciseHistoryHint: "Completed training sessions - even laps, step training and regular sessions - to see progress over time.",
|
||||
exerciseHistoryEmpty: "No completed training sessions yet.",
|
||||
exerciseHistoryEvenLaps: "{streak}-lap streak at target {lap}",
|
||||
exerciseHistoryStepTraining: "{steps} steps, {laps} laps",
|
||||
exerciseHistoryTimer: "{laps} laps, average {lap}",
|
||||
exerciseSessionsCredit: "You completed {count} training session(s) today - nice work!",
|
||||
plan: "Today's practice session",
|
||||
timerSetup: "Set session duration",
|
||||
pushMinutes: "Maximum focus (min)",
|
||||
@@ -374,6 +392,12 @@ function recommendationCopy(recommendation) {
|
||||
};
|
||||
}
|
||||
|
||||
function exerciseKindMeta(kind) {
|
||||
if (kind === "evenLaps") return { emoji: "🎯", titleKey: "evenLapsTitle" };
|
||||
if (kind === "stepTraining") return { emoji: "🪜", titleKey: "stepTrainingTitle" };
|
||||
return { emoji: "⏱️", titleKey: "timerSessionTitle" };
|
||||
}
|
||||
|
||||
function nextMilestoneForLaps(laps) {
|
||||
const presets = [100, 250, 500, 1000, 1500, 2500, 5000];
|
||||
return presets.find((target) => target > laps) || (Math.floor(laps / 1000) + 1) * 1000;
|
||||
@@ -424,9 +448,11 @@ function getLocalDayKey(timestamp) {
|
||||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
function buildProfileMotivation(stats, channelStats = {}) {
|
||||
function buildProfileMotivation(stats, channelStats = {}, exerciseSessionHistory = []) {
|
||||
const todayKey = getLocalDayKey(Date.now());
|
||||
const today = (Array.isArray(stats?.dailySummaries) ? stats.dailySummaries : []).find((day) => day.dateKey === todayKey);
|
||||
const exerciseSessionsToday = (Array.isArray(exerciseSessionHistory) ? exerciseSessionHistory : [])
|
||||
.filter((entry) => getLocalDayKey(new Date(entry.completedAt).getTime()) === todayKey);
|
||||
const activeToday = Boolean(today);
|
||||
const todayLaps = Number(today?.laps || 0);
|
||||
const controlled = activeToday ? Number(stats?.todayControlledLapStreak || 0) : 0;
|
||||
@@ -441,6 +467,9 @@ function buildProfileMotivation(stats, channelStats = {}) {
|
||||
completed: challenge.current >= challenge.target,
|
||||
}));
|
||||
const credits = [];
|
||||
// Completing a guided exercise pass is worth calling out first - it's the thing the driver
|
||||
// most deliberately chose to do, not just background pace/consistency drift.
|
||||
if (exerciseSessionsToday.length) credits.push(t("exerciseSessionsCredit", { count: exerciseSessionsToday.length }));
|
||||
if (todayLaps) credits.push(t("todayLapsCredit", { laps: todayLaps }));
|
||||
if (stats?.trendSampleReady && Number(stats.averageTrendMs || 0) > 0) credits.push(t("paceCredit", { lap: formatLap(stats.averageTrendMs) }));
|
||||
if (stats?.trendSampleReady && Number(stats.consistencyTrendPct || 0) > 0.1) credits.push(t("consistencyCredit", { value: Number(stats.consistencyTrendPct).toFixed(1) }));
|
||||
@@ -494,10 +523,19 @@ function renderProfile(data) {
|
||||
const evenLapsConfig = activeClass?.evenLapsConfig || null;
|
||||
const evenLapsProgress = activeClass?.evenLapsProgress || null;
|
||||
const evenLapsSuggestedTargetMs = stats.bestLapMs ? Math.round(stats.bestLapMs * 1.05) : 0;
|
||||
const evenLapsRunning = Boolean(readExerciseRunState("evenlaps"));
|
||||
const evenLapsRun = readExerciseRunState("evenlaps");
|
||||
const evenLapsRunning = Boolean(evenLapsRun);
|
||||
const stepTrainingConfig = activeClass?.stepTrainingConfig || null;
|
||||
const stepTrainingProgress = activeClass?.stepTrainingProgress || null;
|
||||
const stepTrainingRunning = Boolean(readExerciseRunState("steptraining"));
|
||||
const stepTrainingRun = readExerciseRunState("steptraining");
|
||||
const stepTrainingRunning = Boolean(stepTrainingRun);
|
||||
const exerciseSessionHistory = activeClass?.exerciseSessionHistory || data.exerciseSessionHistory || [];
|
||||
if (evenLapsRun && evenLapsConfig && evenLapsProgress?.currentStreak >= evenLapsConfig.lapCount) {
|
||||
void maybeRecordExerciseCompletion("evenLaps", evenLapsRun.startedAt);
|
||||
}
|
||||
if (stepTrainingRun && stepTrainingProgress?.complete) {
|
||||
void maybeRecordExerciseCompletion("stepTraining", stepTrainingRun.startedAt);
|
||||
}
|
||||
const defaultStepTrainingRows = [
|
||||
{ effort: "calm", lapCount: 5 }, { effort: "controlled", lapCount: 5 }, { effort: "fast", lapCount: 5 },
|
||||
{ effort: "controlled", lapCount: 5 }, { effort: "calm", lapCount: 5 },
|
||||
@@ -505,7 +543,7 @@ function renderProfile(data) {
|
||||
const stepTrainingFormRows = stepTrainingConfig?.steps?.length
|
||||
? [...stepTrainingConfig.steps, ...Array(Math.max(0, 5 - stepTrainingConfig.steps.length)).fill({ effort: "calm", lapCount: 0 })].slice(0, 5)
|
||||
: defaultStepTrainingRows;
|
||||
const motivation = buildProfileMotivation(stats, channelStats);
|
||||
const motivation = buildProfileMotivation(stats, channelStats, exerciseSessionHistory);
|
||||
const recommendationText = recommendationCopy(recommendation);
|
||||
const timerState = readTimerState();
|
||||
const timerConfig = getTimerConfig(timerState);
|
||||
@@ -546,17 +584,22 @@ function renderProfile(data) {
|
||||
? `<img src="${escapeHtml(branding.logoDataUrl)}" alt="" />`
|
||||
: `<div class="profile-brand-mark">RC</div>`;
|
||||
const goalMarkup = goals.length
|
||||
? goals.map((goal) => `
|
||||
? goals.map((goal) => {
|
||||
const isSessions = goal.metric === "sessions";
|
||||
const meta = exerciseKindMeta(goal.exerciseKind);
|
||||
const unitSuffix = isSessions ? ` ${meta.emoji} ${escapeHtml(t(meta.titleKey))}` : "";
|
||||
return `
|
||||
<article class="profile-goal ${goal.reached ? "reached" : ""}">
|
||||
<div class="profile-goal-row">
|
||||
<strong>${escapeHtml(goal.title || t("reachLaps", { laps: goal.targetLaps }))}</strong>
|
||||
<span>${goal.currentLaps} / ${goal.targetLaps}</span>
|
||||
<strong>${escapeHtml(goal.title || (isSessions ? t("reachSessions", { count: goal.targetLaps }) : t("reachLaps", { laps: goal.targetLaps })))}</strong>
|
||||
<span>${goal.currentLaps} / ${goal.targetLaps}${unitSuffix}</span>
|
||||
</div>
|
||||
<div class="profile-progress"><span style="width:${Number(goal.percent || 0).toFixed(2)}%"></span></div>
|
||||
${goal.reward ? `<p><span class="profile-mini-label">${escapeHtml(t("reward"))}</span><br />${escapeHtml(goal.reward)}</p>` : ""}
|
||||
${goal.claimed ? `<span class="profile-mini-label">${escapeHtml(t("rewardDelivered"))}</span>` : goal.reached ? `<span class="profile-mini-label">${escapeHtml(t("goalReached"))}</span>` : ""}
|
||||
</article>
|
||||
`).join("")
|
||||
`;
|
||||
}).join("")
|
||||
: `<p class="profile-empty">${escapeHtml(t("noGoals"))}</p>`;
|
||||
const historyRows = stats.dailySummaries.length
|
||||
? stats.dailySummaries.slice(0, 12).map((day) => `
|
||||
@@ -826,6 +869,35 @@ function renderProfile(data) {
|
||||
</table>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<details class="profile-card profile-disclosure ${visibility.history ? "" : "is-hidden"}" data-persist-open="exerciseHistory" ${openSections.has("exerciseHistory") ? "open" : ""} style="margin-top:14px">
|
||||
<summary class="profile-card-head"><h2>${escapeHtml(t("exerciseHistoryTitle"))}</h2><span>+</span></summary>
|
||||
<div class="profile-card-body">
|
||||
<p class="hint">${escapeHtml(t("exerciseHistoryHint"))}</p>
|
||||
${exerciseSessionHistory.length ? `
|
||||
<ul class="profile-exercise-history">
|
||||
${exerciseSessionHistory.map((entry) => {
|
||||
const meta = exerciseKindMeta(entry.kind);
|
||||
const date = new Date(entry.completedAt).toLocaleString(language, { dateStyle: "short", timeStyle: "short" });
|
||||
const detail = entry.kind === "evenLaps"
|
||||
? t("exerciseHistoryEvenLaps", { streak: entry.summary?.streak ?? "-", lap: formatLap(entry.summary?.targetMs) })
|
||||
: entry.kind === "stepTraining"
|
||||
? t("exerciseHistoryStepTraining", { steps: entry.summary?.totalSteps ?? "-", laps: entry.summary?.totalLaps ?? "-" })
|
||||
: t("exerciseHistoryTimer", { laps: entry.summary?.laps ?? "-", lap: formatLap(entry.summary?.averageLapMs) });
|
||||
return `
|
||||
<li class="profile-exercise-history-row">
|
||||
<span class="profile-exercise-history-emoji">${meta.emoji}</span>
|
||||
<div>
|
||||
<strong>${escapeHtml(t(meta.titleKey))}</strong>
|
||||
<small>${escapeHtml(date)} · ${escapeHtml(detail)}</small>
|
||||
</div>
|
||||
</li>
|
||||
`;
|
||||
}).join("")}
|
||||
</ul>
|
||||
` : `<p class="profile-empty">${escapeHtml(t("exerciseHistoryEmpty"))}</p>`}
|
||||
</div>
|
||||
</details>
|
||||
`;
|
||||
const markerForm = document.getElementById("publicTrainingMarkerForm");
|
||||
const draft = markerDrafts.get(selectedClassId);
|
||||
@@ -946,6 +1018,47 @@ function writePracticeSummaryDismissedFor(startedAtValue) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Remembers which run (by startedAt) of each of the three exercise kinds has already had a
|
||||
// completion request sent for it, so a background re-render (this function runs on every
|
||||
// renderProfile(), not just once) doesn't keep re-POSTing while the completed state persists.
|
||||
function getExerciseRecordedStorageKey(kind) {
|
||||
return `rc-training-${kind}-recorded:${shareToken}:${selectedClassId || "default"}`;
|
||||
}
|
||||
|
||||
function readExerciseRecordedFor(kind) {
|
||||
try {
|
||||
return localStorage.getItem(getExerciseRecordedStorageKey(kind)) || "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
function writeExerciseRecordedFor(kind, startedAtValue) {
|
||||
try {
|
||||
localStorage.setItem(getExerciseRecordedStorageKey(kind), String(startedAtValue));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The driver's browser only ever *asks* the server to record a completion - the server
|
||||
// independently recomputes the outcome from real ledger laps and refuses if it disagrees (see
|
||||
// recordPublicExerciseSession in server/public_training_profile.js). This just avoids sending
|
||||
// that request more than once per run.
|
||||
async function maybeRecordExerciseCompletion(kind, startedAt, extra = {}) {
|
||||
if (!startedAt || !selectedClassId) return;
|
||||
if (readExerciseRecordedFor(kind) === String(startedAt)) return;
|
||||
writeExerciseRecordedFor(kind, startedAt);
|
||||
try {
|
||||
const response = await fetch(`/public-training/api/${encodeURIComponent(shareToken)}/exercise-sessions`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ classId: selectedClassId, kind, startedAgoMs: Math.max(0, Date.now() - startedAt), ...extra }),
|
||||
});
|
||||
if (response.ok) await loadProfile();
|
||||
} catch {
|
||||
// best-effort - a missed credit for one session is not worth retry complexity here
|
||||
}
|
||||
}
|
||||
|
||||
// The two guided exercises track progress by laps completed since the driver tapped
|
||||
// "start", not by elapsed time, so unlike the timer above there is no pause/duration to
|
||||
// manage locally - just a start timestamp (or none) per class, mirrored to the server as
|
||||
@@ -1123,6 +1236,7 @@ function updateTimerDisplay() {
|
||||
lastTimerPhase = phaseName;
|
||||
if (justFinished) {
|
||||
speak(t("finishCue"));
|
||||
void maybeRecordExerciseCompletion("timer", state.startedAt, { windowMs: timerDurationMs });
|
||||
// Show the practice summary the moment the pass actually finishes, rather than
|
||||
// waiting for the next background poll (up to 10s away) to pick it up.
|
||||
if (profileData) renderProfile(profileData);
|
||||
|
||||
Reference in new issue
Block a user