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:
larssandandClaude Sonnet 5 committed 2026-09-09 20:43:47 +02:00
1 parent bed0dfd9f2
commit 1c4a06b69e
14 files changed
+800 -52

No files matched your search

+108 -13
View File
@@ -1,6 +1,8 @@
import { sortValuesAttribute } from "./list_sorting.js";
import { getDriverProfileGroups, getDriverProfileReferences } from "./driver_profile_logic.js";
const EXERCISE_KIND_EMOJI = { timer: "⏱️", evenLaps: "🎯", stepTraining: "🪜" };
function renderStintRow(row, { t, escapeHtml, formatLap, formatRaceClock }) {
const paceRetention = row.endChangeMs == null
? "-"
@@ -32,6 +34,7 @@ export function renderTrainingView(deps) {
const moreStatsWasOpen = Boolean(document.getElementById("trainingMoreStats")?.open);
const goalsSharingElement = document.getElementById("trainingGoalsSharing");
const goalsSharingWasOpen = goalsSharingElement ? goalsSharingElement.open : true;
const exerciseHistoryWasOpen = Boolean(document.getElementById("trainingExerciseHistory")?.open);
const {
state,
dom,
@@ -56,6 +59,8 @@ export function renderTrainingView(deps) {
buildTrainingMissions,
buildTrainingHighlights,
getClubTrainingGoalProgress,
countDriverExerciseSessions,
countExerciseSessions,
buildTrainingPaceBuckets,
buildTrainingWeekdayStats,
buildTrainingStintAnalysis,
@@ -92,7 +97,7 @@ export function renderTrainingView(deps) {
}
if (!selectedProfileId || !selectedProfile) {
renderTrainingOverview({ state, dom, t, escapeHtml, formatLap, uid, saveState, profiles, buildDriverTrainingStats, getNextTrainingMilestone, getClubTrainingGoalProgress, setSelectedDriverId, setSelectedClassId, renderView });
renderTrainingOverview({ state, dom, t, escapeHtml, formatLap, uid, saveState, profiles, buildDriverTrainingStats, getNextTrainingMilestone, getClubTrainingGoalProgress, countExerciseSessions, setSelectedDriverId, setSelectedClassId, renderView });
return;
}
@@ -135,6 +140,26 @@ export function renderTrainingView(deps) {
profileReferences.has(String(goal.driverId || ""))
&& (!goal.classId || String(goal.classId) === selectedClassId)
));
const exerciseSessionHistory = (Array.isArray(state.training.exerciseSessions) ? state.training.exerciseSessions : [])
.filter((entry) => profileReferences.has(String(entry?.driverId || "")) && String(entry?.classId || "") === selectedClassId)
.slice(0, 15);
const exerciseHistoryMarkup = exerciseSessionHistory.length
? exerciseSessionHistory.map((entry) => {
const meta = { timer: { emoji: EXERCISE_KIND_EMOJI.timer, label: t("training.exercise_kind_timer") }, evenLaps: { emoji: EXERCISE_KIND_EMOJI.evenLaps, label: t("training.exercise_kind_evenLaps") }, stepTraining: { emoji: EXERCISE_KIND_EMOJI.stepTraining, label: t("training.exercise_kind_stepTraining") } }[entry.kind] || { emoji: "", label: entry.kind };
const date = new Date(entry.completedAt).toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" });
const detail = entry.kind === "evenLaps"
? t("training.exercise_history_evenLaps", { streak: entry.summary?.streak ?? "-", lap: formatLap(entry.summary?.targetMs) })
: entry.kind === "stepTraining"
? t("training.exercise_history_stepTraining", { steps: entry.summary?.totalSteps ?? "-", laps: entry.summary?.totalLaps ?? "-" })
: t("training.exercise_history_timer", { laps: entry.summary?.laps ?? "-", lap: formatLap(entry.summary?.averageLapMs) });
return `
<li class="training-exercise-history-row">
<span>${meta.emoji}</span>
<div><strong>${escapeHtml(meta.label)}</strong><small>${escapeHtml(date)} - ${escapeHtml(detail)}</small></div>
</li>
`;
}).join("")
: `<p class="hint">${escapeHtml(t("training.exercise_history_empty"))}</p>`;
const profileShare = (state.training.shares || []).find((share) => profileReferences.has(String(share.driverId || "")) && share.enabled);
const publicBaseUrl = normalizePublicBaseUrl(state.settings?.publicBaseUrl);
const localBaseUrl = window.location.origin;
@@ -163,21 +188,27 @@ export function renderTrainingView(deps) {
const goalMarkup = goals.length
? goals.map((goal) => {
const progress = getTrainingGoalProgress(goal, stats);
const isSessions = goal.metric === "sessions";
const sessionCount = isSessions ? countDriverExerciseSessions(state, selectedProfileId, selectedClassId, goal.exerciseKind) : 0;
const progress = getTrainingGoalProgress(goal, stats, sessionCount);
const emoji = isSessions ? EXERCISE_KIND_EMOJI[goal.exerciseKind] || "" : "";
const unitLabel = isSessions ? t(`training.exercise_kind_${goal.exerciseKind}`) : "";
const statusClass = goal.claimedAt ? "claimed" : progress.reached ? "reached" : "active";
const statusLabel = goal.claimedAt
? t("training.goal_claimed")
: progress.reached
? t("training.goal_reached")
: isSessions
? t("training.goal_remaining_sessions", { count: progress.remainingLaps })
: t("training.goal_remaining", { laps: progress.remainingLaps });
return `
<article class="training-goal ${statusClass}">
<div class="training-goal-head">
<div>
<span class="training-kicker">${escapeHtml(statusLabel)}</span>
<h4>${escapeHtml(goal.title || t("training.default_goal_title", { laps: goal.targetLaps }))}</h4>
<h4>${escapeHtml(goal.title || (isSessions ? t("training.default_goal_title_sessions", { count: goal.targetLaps, kind: unitLabel }) : t("training.default_goal_title", { laps: goal.targetLaps })))}</h4>
</div>
<strong>${progress.currentLaps} / ${progress.targetLaps}</strong>
<strong>${progress.currentLaps} / ${progress.targetLaps}${isSessions ? ` ${emoji}` : ""}</strong>
</div>
<div class="training-progress" aria-label="${escapeHtml(t("training.goal_progress"))}">
<span style="width:${progress.percent.toFixed(2)}%"></span>
@@ -523,6 +554,16 @@ export function renderTrainingView(deps) {
</section>
` : ""}
<details class="training-disclosure mt-16" id="trainingExerciseHistory" ${exerciseHistoryWasOpen ? "open" : ""}>
<summary>
<span><strong>${escapeHtml(t("training.exercise_history_title"))}</strong><small>${escapeHtml(t("training.exercise_history_hint"))}</small></span>
<span class="training-disclosure-arrow">+</span>
</summary>
<div class="training-disclosure-body">
<ul class="training-exercise-history">${exerciseHistoryMarkup}</ul>
</div>
</details>
<div class="training-secondary">
<details class="training-disclosure" id="trainingGoalsSharing" ${goalsSharingWasOpen ? "open" : ""}>
<summary>
@@ -534,10 +575,19 @@ export function renderTrainingView(deps) {
<section class="training-simple-section">
<h3>${escapeHtml(t("training.new_goal"))}</h3>
<form id="training-goal-form" class="form-grid training-goal-form">
<label>${escapeHtml(t("training.target_laps"))}<input type="number" name="targetLaps" min="1" step="1" value="500" required /></label>
<div class="training-presets" aria-label="${escapeHtml(t("training.quick_targets"))}">
<label>${escapeHtml(t("training.goal_type"))}
<select id="trainingGoalType" name="goalType">
<option value="laps">${escapeHtml(t("training.goal_type_laps"))}</option>
<option value="evenLaps">${escapeHtml(t("training.goal_type_evenLaps"))}</option>
<option value="stepTraining">${escapeHtml(t("training.goal_type_stepTraining"))}</option>
<option value="timer">${escapeHtml(t("training.goal_type_timer"))}</option>
</select>
</label>
<label id="trainingGoalLapsField">${escapeHtml(t("training.target_laps"))}<input type="number" name="targetLaps" min="1" step="1" value="500" /></label>
<div id="trainingGoalLapsPresets" class="training-presets" aria-label="${escapeHtml(t("training.quick_targets"))}">
${[500, 1000, 1500].map((value) => `<button type="button" class="btn btn-mini training-preset" data-laps="${value}">${value}</button>`).join("")}
</div>
<label id="trainingGoalSessionsField" hidden>${escapeHtml(t("training.target_sessions"))}<input type="number" name="targetSessions" min="1" step="1" value="10" /></label>
<label>${escapeHtml(t("training.goal_name"))}<input name="title" placeholder="${escapeHtml(t("training.goal_name_placeholder"))}" /></label>
<label>${escapeHtml(t("training.reward"))}<input name="reward" placeholder="${escapeHtml(t("training.reward_placeholder"))}" /></label>
<button class="btn btn-primary" type="submit">${escapeHtml(t("training.add_goal"))}</button>
@@ -837,15 +887,32 @@ export function renderTrainingView(deps) {
});
});
const updateGoalTypeFields = () => {
const goalType = document.getElementById("trainingGoalType")?.value || "laps";
const isSessions = goalType !== "laps";
const lapsField = document.getElementById("trainingGoalLapsField");
const lapsPresets = document.getElementById("trainingGoalLapsPresets");
const sessionsField = document.getElementById("trainingGoalSessionsField");
if (lapsField) lapsField.hidden = isSessions;
if (lapsPresets) lapsPresets.hidden = isSessions;
if (sessionsField) sessionsField.hidden = !isSessions;
};
document.getElementById("trainingGoalType")?.addEventListener("change", updateGoalTypeFields);
updateGoalTypeFields();
document.getElementById("training-goal-form")?.addEventListener("submit", (event) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
const targetLaps = Math.max(1, Math.round(Number(form.get("targetLaps") || 0) || 0));
const goalType = String(form.get("goalType") || "laps");
const isSessions = goalType !== "laps";
state.training.goals.push({
id: uid("goal"),
driverId: selectedProfileId,
classId: selectedClassId,
targetLaps,
targetLaps: Math.max(1, Math.round(Number(form.get("targetLaps") || 0) || 0)),
metric: isSessions ? "sessions" : "laps",
exerciseKind: isSessions ? goalType : "",
targetSessions: Math.max(1, Math.round(Number(form.get("targetSessions") || 0) || 0)),
title: String(form.get("title") || "").trim(),
reward: String(form.get("reward") || "").trim(),
createdAt: new Date().toISOString(),
@@ -979,7 +1046,7 @@ export function buildTrainingProgressFeed(rows, limit = 6) {
});
}
function renderTrainingOverview({ state, dom, t, escapeHtml, formatLap, uid, saveState, profiles, buildDriverTrainingStats, getNextTrainingMilestone, getClubTrainingGoalProgress, setSelectedDriverId, setSelectedClassId, renderView }) {
function renderTrainingOverview({ state, dom, t, escapeHtml, formatLap, uid, saveState, profiles, buildDriverTrainingStats, getNextTrainingMilestone, getClubTrainingGoalProgress, countExerciseSessions, setSelectedDriverId, setSelectedClassId, renderView }) {
const rows = buildTrainingOverviewRows(state, profiles, buildDriverTrainingStats);
const progressFeed = buildTrainingProgressFeed(rows);
const ledger = Array.isArray(state.training?.ledger) ? state.training.ledger : [];
@@ -1026,17 +1093,20 @@ function renderTrainingOverview({ state, dom, t, escapeHtml, formatLap, uid, sav
</tr>
`;
}).join("");
const clubGoalIsSessions = clubGoal?.metric === "sessions";
const clubGoalEmoji = clubGoalIsSessions ? EXERCISE_KIND_EMOJI[clubGoal.exerciseKind] || "" : "";
const clubGoalUnitLabel = clubGoalIsSessions ? t(`training.exercise_kind_${clubGoal.exerciseKind}`) : "";
const clubGoalMarkup = clubGoal && clubGoalProgress ? `
<div class="training-club-goal ${clubGoalProgress.reached ? "is-reached" : ""}">
<div class="training-club-goal-head">
<div>
<span class="training-kicker">${escapeHtml(t(clubGoal.celebratedAt ? "training.club_goal_celebrated" : clubGoalProgress.reached ? "training.club_goal_reached" : "training.club_goal_active"))}</span>
<h3>${escapeHtml(clubGoal.title || t("training.club_goal_default", { laps: clubGoal.targetLaps }))}</h3>
<h3>${escapeHtml(clubGoal.title || (clubGoalIsSessions ? t("training.club_goal_default_sessions", { count: clubGoal.targetSessions, kind: clubGoalUnitLabel }) : t("training.club_goal_default", { laps: clubGoal.targetLaps })))}</h3>
</div>
<strong>${clubGoalProgress.currentLaps} / ${clubGoalProgress.targetLaps}</strong>
<strong>${clubGoalProgress.currentLaps} / ${clubGoalProgress.targetLaps}${clubGoalIsSessions ? ` ${clubGoalEmoji}` : ""}</strong>
</div>
<div class="training-progress"><span style="width:${clubGoalProgress.percent.toFixed(2)}%"></span></div>
<p>${escapeHtml(t("training.club_goal_remaining", { laps: clubGoalProgress.remainingLaps }))}</p>
<p>${escapeHtml(clubGoalIsSessions ? t("training.club_goal_remaining_sessions", { count: clubGoalProgress.remainingLaps }) : t("training.club_goal_remaining", { laps: clubGoalProgress.remainingLaps }))}</p>
${clubGoal.reward ? `<p><b>${escapeHtml(t("training.reward"))}:</b> ${escapeHtml(clubGoal.reward)}</p>` : ""}
<div class="actions">
${clubGoalProgress.reached && !clubGoal.celebratedAt ? `<button class="btn btn-primary" id="trainingClubGoalCelebrate" type="button">${escapeHtml(t("training.club_goal_mark_celebrated"))}</button>` : ""}
@@ -1077,7 +1147,16 @@ function renderTrainingOverview({ state, dom, t, escapeHtml, formatLap, uid, sav
<details class="training-club-goal-editor">
<summary>${escapeHtml(t(clubGoal ? "training.club_goal_new" : "training.club_goal_create"))}</summary>
<form id="trainingClubGoalForm" class="form-grid training-club-goal-form">
<label>${escapeHtml(t("training.target_laps"))}<input type="number" name="targetLaps" min="1" step="1" value="10000" required /></label>
<label>${escapeHtml(t("training.goal_type"))}
<select id="trainingClubGoalType" name="goalType">
<option value="laps">${escapeHtml(t("training.goal_type_laps"))}</option>
<option value="evenLaps">${escapeHtml(t("training.goal_type_evenLaps"))}</option>
<option value="stepTraining">${escapeHtml(t("training.goal_type_stepTraining"))}</option>
<option value="timer">${escapeHtml(t("training.goal_type_timer"))}</option>
</select>
</label>
<label id="trainingClubGoalLapsField">${escapeHtml(t("training.target_laps"))}<input type="number" name="targetLaps" min="1" step="1" value="10000" /></label>
<label id="trainingClubGoalSessionsField" hidden>${escapeHtml(t("training.target_sessions"))}<input type="number" name="targetSessions" min="1" step="1" value="50" /></label>
<label>${escapeHtml(t("training.goal_name"))}<input name="title" maxlength="80" placeholder="${escapeHtml(t("training.club_goal_name_placeholder"))}" /></label>
<label>${escapeHtml(t("training.reward"))}<input name="reward" maxlength="120" placeholder="${escapeHtml(t("training.club_goal_reward_placeholder"))}" /></label>
<button class="btn btn-primary" type="submit">${escapeHtml(t("training.club_goal_start"))}</button>
@@ -1112,15 +1191,31 @@ function renderTrainingOverview({ state, dom, t, escapeHtml, formatLap, uid, sav
setSelectedClassId("");
renderView();
});
const updateClubGoalTypeFields = () => {
const goalType = document.getElementById("trainingClubGoalType")?.value || "laps";
const isSessions = goalType !== "laps";
const lapsField = document.getElementById("trainingClubGoalLapsField");
const sessionsField = document.getElementById("trainingClubGoalSessionsField");
if (lapsField) lapsField.hidden = isSessions;
if (sessionsField) sessionsField.hidden = !isSessions;
};
document.getElementById("trainingClubGoalType")?.addEventListener("change", updateClubGoalTypeFields);
updateClubGoalTypeFields();
document.getElementById("trainingClubGoalForm")?.addEventListener("submit", (event) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
const goalType = String(form.get("goalType") || "laps");
const isSessions = goalType !== "laps";
state.training.clubGoal = {
id: uid("club_goal"),
title: String(form.get("title") || "").trim(),
reward: String(form.get("reward") || "").trim(),
targetLaps: Math.max(1, Math.round(Number(form.get("targetLaps") || 0) || 0)),
baselineLaps: ledger.length,
metric: isSessions ? "sessions" : "laps",
exerciseKind: isSessions ? goalType : "",
targetSessions: Math.max(1, Math.round(Number(form.get("targetSessions") || 0) || 0)),
baselineSessions: countExerciseSessions(state.training.exerciseSessions, { kind: goalType }),
createdAt: new Date().toISOString(),
celebratedAt: "",
};