wip: слияние прода-версии с портированными фичами (до merge iovi)
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
// frontend/js/render/dashboard-screen.js
|
||||
|
||||
import { state } from '../state.js';
|
||||
import { drawExerciseProgress, drawBodyMetricsGraph } from './dashboard.js';
|
||||
|
||||
export function renderDashboard() {
|
||||
const app = document.getElementById('app');
|
||||
if (!app) return;
|
||||
|
||||
app.innerHTML = `
|
||||
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
|
||||
<h2>📊 Статистика</h2>
|
||||
<button class="btn btn-small btn-secondary" onclick="App.backToMain()">← Назад</button>
|
||||
</div>
|
||||
|
||||
<!-- Секция 1: Прогресс упражнений -->
|
||||
<div class="card mb-20">
|
||||
<h3>💪 Прогресс упражнения</h3>
|
||||
<div class="field-group">
|
||||
<label>Выберите упражнение</label>
|
||||
<select id="dash-ex-select" onchange="DashboardLogic.updateExerciseChart()">
|
||||
<option value="">— Выберите —</option>
|
||||
${getUniqueExercises().map(ex => `<option value="${ex}">${ex}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<canvas id="chart-exercise" width="400" height="200" style="width:100%; background:#1e1e1e; border-radius:8px;"></canvas>
|
||||
<p class="text-muted text-small mt-10">Показаны макс. вес и повторения за последние 10 тренировок.</p>
|
||||
</div>
|
||||
|
||||
<!-- Секция 2: Динамика тела -->
|
||||
<div class="card">
|
||||
<h3>⚖️ Динамика тела</h3>
|
||||
<div class="field-row">
|
||||
<div class="field-group">
|
||||
<label>Клиент (если тренер)</label>
|
||||
<select id="dash-client-select" onchange="DashboardLogic.updateBodyChart()">
|
||||
<option value="">Личные замеры</option>
|
||||
${state.clients.map(c => `<option value="${c.id}">${c.full_name}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<div class="field-group">
|
||||
<label>Тип замера</label>
|
||||
<select id="dash-metric-select" onchange="DashboardLogic.updateBodyChart()">
|
||||
${state.metricTypes.map(mt => `<option value="${mt.id}">${mt.name} (${mt.unit})</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<canvas id="chart-body" width="400" height="200" style="width:100%; background:#1e1e1e; border-radius:8px;"></canvas>
|
||||
</div>
|
||||
`;
|
||||
|
||||
window.DashboardLogic = {
|
||||
updateExerciseChart: () => {
|
||||
const select = document.getElementById('dash-ex-select');
|
||||
const canvas = document.getElementById('chart-exercise');
|
||||
if (select.value) {
|
||||
drawExerciseProgress(canvas, select.value);
|
||||
} else {
|
||||
const ctx = canvas.getContext('2d');
|
||||
ctx.clearRect(0,0,canvas.width,canvas.height);
|
||||
ctx.fillStyle='#666';
|
||||
ctx.textAlign='center';
|
||||
ctx.fillText('Выберите упражнение выше', canvas.width/2, canvas.height/2);
|
||||
}
|
||||
},
|
||||
updateBodyChart: () => {
|
||||
const clientSel = document.getElementById('dash-client-select');
|
||||
const metricSel = document.getElementById('dash-metric-select');
|
||||
const canvas = document.getElementById('chart-body');
|
||||
|
||||
const clientId = clientSel.value ? parseInt(clientSel.value) : null;
|
||||
const metricId = metricSel.value ? parseInt(metricSel.value) : null;
|
||||
|
||||
if (metricId) {
|
||||
drawBodyMetricsGraph(canvas, clientId, metricId);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Первичная отрисовка (пустые состояния)
|
||||
DashboardLogic.updateExerciseChart();
|
||||
if(state.metricTypes.length > 0) {
|
||||
document.getElementById('dash-metric-select').value = state.metricTypes[0].id;
|
||||
DashboardLogic.updateBodyChart();
|
||||
}
|
||||
}
|
||||
|
||||
function getUniqueExercises() {
|
||||
const set = new Set();
|
||||
state.workouts.forEach(w => {
|
||||
w.exercises.forEach(ex => {
|
||||
set.add(ex.name);
|
||||
});
|
||||
});
|
||||
return Array.from(set).sort();
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
// frontend/js/render/dashboard.js
|
||||
|
||||
import { state } from '../state.js';
|
||||
import { formatDate } from '../utils.js';
|
||||
|
||||
/**
|
||||
* Рисует линейный график прогресса упражнения
|
||||
* @param {HTMLCanvasElement} canvas
|
||||
* @param {string} exerciseName
|
||||
*/
|
||||
export function drawExerciseProgress(canvas, exerciseName) {
|
||||
const ctx = canvas.getContext('2d');
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
|
||||
const history = getCumulativeExerciseHistory(exerciseName);
|
||||
|
||||
if (history.length < 2) {
|
||||
drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 тренировки");
|
||||
return;
|
||||
}
|
||||
|
||||
// Находим максимальный ИТОГОВЫЙ объем для масштабирования оси Y
|
||||
const maxVolume = Math.max(...history.map(h => h.totalVolume));
|
||||
|
||||
const padding = { top: 20, right: 20, bottom: 30, left: 40 };
|
||||
const chartW = width - padding.left - padding.right;
|
||||
const chartH = height - padding.top - padding.bottom;
|
||||
|
||||
// Рисуем сетку (используем maxVolume для оси Y)
|
||||
drawGridAndAxes(ctx, padding, chartW, chartH, maxVolume, 'Дата', 'Общий вес (кг)');
|
||||
|
||||
// Рисуем новый график со стеком
|
||||
drawCumulativeVolumeChart(ctx, history, padding, chartW, chartH, maxVolume);
|
||||
|
||||
// Легенда (обновленная)
|
||||
drawLegend(ctx, width, [
|
||||
{ color: '#bb86fc', label: 'Итоговый объем' },
|
||||
{ color: 'rgba(187, 134, 252, 0.4)', label: 'Накопление по подходам' }
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Рисует график динамики телесных замеров
|
||||
* @param {HTMLCanvasElement} canvas
|
||||
* @param {number|null} clientId - null для личных замеров
|
||||
* @param {number} metricTypeId - ID типа замера (например, вес)
|
||||
*/
|
||||
export function drawBodyMetricsGraph(canvas, clientId, metricTypeId) {
|
||||
const ctx = canvas.getContext('2d');
|
||||
const width = canvas.width;
|
||||
const height = canvas.height;
|
||||
|
||||
ctx.clearRect(0, 0, width, height);
|
||||
|
||||
// Фильтруем замеры
|
||||
const metrics = state.bodyMetrics
|
||||
.filter(m => m.client_id == clientId)
|
||||
.sort((a, b) => new Date(a.date) - new Date(b.date));
|
||||
|
||||
// Извлекаем значения конкретного типа
|
||||
const dataPoints = [];
|
||||
metrics.forEach(m => {
|
||||
const valObj = m.values?.find(v => v.metric_type_id == metricTypeId);
|
||||
if (valObj && valObj.value !== undefined && valObj.value !== null) {
|
||||
dataPoints.push({ date: new Date(m.date), value: parseFloat(valObj.value) });
|
||||
}
|
||||
});
|
||||
|
||||
if (dataPoints.length < 2) {
|
||||
drawEmptyState(ctx, width, height, "Недостаточно данных\nНужно минимум 2 замера");
|
||||
return;
|
||||
}
|
||||
|
||||
const minVal = Math.min(...dataPoints.map(p => p.value));
|
||||
const maxVal = Math.max(...dataPoints.map(p => p.value));
|
||||
const range = maxVal - minVal || 1; // Защита от деления на ноль
|
||||
|
||||
const padding = { top: 20, right: 20, bottom: 30, left: 40 };
|
||||
const chartW = width - padding.left - padding.right;
|
||||
const chartH = height - padding.top - padding.bottom;
|
||||
|
||||
// Простая ось Y (значения)
|
||||
ctx.strokeStyle = '#333';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(padding.left, padding.top);
|
||||
ctx.lineTo(padding.left, height - padding.bottom);
|
||||
ctx.stroke();
|
||||
|
||||
// Подписи осей Y
|
||||
ctx.fillStyle = '#b0b0b0';
|
||||
ctx.font = '10px sans-serif';
|
||||
ctx.textAlign = 'right';
|
||||
for (let i = 0; i <= 4; i++) {
|
||||
const y = height - padding.bottom - (i / 4) * chartH;
|
||||
const val = minVal + (range * i / 4);
|
||||
ctx.fillText(val.toFixed(1), padding.left - 5, y + 3);
|
||||
|
||||
// Горизонтальная линия сетки
|
||||
ctx.strokeStyle = '#2c2c2c';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(padding.left, y);
|
||||
ctx.lineTo(width - padding.right, y);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// Рисуем точку начала и конца по X (дата)
|
||||
const firstDate = dataPoints[0].date.getTime();
|
||||
const lastDate = dataPoints[dataPoints.length - 1].date.getTime();
|
||||
const timeRange = lastDate - firstDate || 1;
|
||||
|
||||
ctx.strokeStyle = '#bb86fc'; // Цвет линии графика
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
|
||||
dataPoints.forEach((p, index) => {
|
||||
const x = padding.left + ((p.date.getTime() - firstDate) / timeRange) * chartW;
|
||||
const y = height - padding.bottom - ((p.value - minVal) / range) * chartH;
|
||||
|
||||
if (index === 0) ctx.moveTo(x, y);
|
||||
else ctx.lineTo(x, y);
|
||||
|
||||
// Точки
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillRect(x - 2, y - 2, 4, 4);
|
||||
});
|
||||
ctx.stroke();
|
||||
|
||||
// Подпись даты слева и справа
|
||||
ctx.fillStyle = '#b0b0b0';
|
||||
ctx.textAlign = 'left';
|
||||
ctx.fillText(formatShortDate(dataPoints[0].date.toISOString()), padding.left, height - 10);
|
||||
ctx.textAlign = 'right';
|
||||
ctx.fillText(formatShortDate(dataPoints[dataPoints.length-1].date.toISOString()), width - padding.right, height - 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Собирает историю с накопительным весом по каждому подходу
|
||||
*/
|
||||
function getCumulativeExerciseHistory(name) {
|
||||
const normalized = name.trim().toLowerCase();
|
||||
const history = [];
|
||||
|
||||
state.workouts.forEach(w => {
|
||||
w.exercises.forEach(ex => {
|
||||
if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) {
|
||||
let currentCumulativeWeight = 0;
|
||||
const cumulativePoints = [];
|
||||
|
||||
ex.sets.forEach(s => {
|
||||
// Учитываем вес подхода (для дроп-сетов можно брать средний или максимальный, здесь берем основной)
|
||||
const setWeight = s.isDropset && s.subSets
|
||||
? Math.max(...s.subSets.map(ss => ss.weight))
|
||||
: s.weight;
|
||||
|
||||
// Объем подхода = вес * повторения (или просто вес, если вы считаете тоннаж)
|
||||
// В вашем примере (15, 30, 45, 60) вы суммируете именно вес подходов.
|
||||
// Если нужно суммировать тоннаж (вес * повторы), замените на: setWeight * s.reps
|
||||
const volume = setWeight * s.reps;
|
||||
|
||||
currentCumulativeWeight += volume;
|
||||
cumulativePoints.push(currentCumulativeWeight);
|
||||
});
|
||||
|
||||
history.push({
|
||||
date: new Date(w.startTime),
|
||||
cumulativePoints: cumulativePoints, // [15, 30, 45, 60]
|
||||
totalVolume: currentCumulativeWeight // 60
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
history.sort((a, b) => a.date - b.date);
|
||||
return history.slice(-10); // Последние 10 тренировок
|
||||
}
|
||||
|
||||
// --- Вспомогательные функции ---
|
||||
|
||||
function getExerciseHistoryData(name) {
|
||||
const normalized = name.trim().toLowerCase();
|
||||
const history = [];
|
||||
|
||||
// Собираем из всех тренировок текущего пользователя (или клиента, если режим тренера реализован глобально)
|
||||
// Здесь упрощение: берем все тренировки из state.workouts
|
||||
state.workouts.forEach(w => {
|
||||
w.exercises.forEach(ex => {
|
||||
if (ex.name.trim().toLowerCase() === normalized && ex.sets.length > 0) {
|
||||
history.push({
|
||||
date: new Date(w.startTime),
|
||||
sets: ex.sets
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Сортируем по дате
|
||||
history.sort((a, b) => a.date - b.date);
|
||||
return history.slice(-10); // Берем последние 10 тренировок для читаемости
|
||||
}
|
||||
|
||||
function getMaxWeightInSet(historyItem) {
|
||||
let max = 0;
|
||||
historyItem.sets.forEach(s => {
|
||||
if (s.isDropset && s.subSets) {
|
||||
s.subSets.forEach(ss => { if (ss.weight > max) max = ss.weight; });
|
||||
} else if (s.weight > max) {
|
||||
max = s.weight;
|
||||
}
|
||||
});
|
||||
return max;
|
||||
}
|
||||
|
||||
function getMaxRepsInSet(historyItem) {
|
||||
let max = 0;
|
||||
historyItem.sets.forEach(s => {
|
||||
if (s.isDropset && s.subSets) {
|
||||
s.subSets.forEach(ss => { if (ss.reps > max) max = ss.reps; });
|
||||
} else if (s.reps > max) {
|
||||
max = s.reps;
|
||||
}
|
||||
});
|
||||
return max;
|
||||
}
|
||||
|
||||
function drawGridAndAxes(ctx, pad, cw, ch, maxY, maxXAxisLabel, yAxisLabel) {
|
||||
ctx.strokeStyle = '#333';
|
||||
ctx.lineWidth = 1;
|
||||
|
||||
// Ось Y
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(pad.left, pad.top);
|
||||
ctx.lineTo(pad.left, ch + pad.top);
|
||||
ctx.stroke();
|
||||
|
||||
// Ось X
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(pad.left, ch + pad.top);
|
||||
ctx.lineTo(cw + pad.left, ch + pad.top);
|
||||
ctx.stroke();
|
||||
|
||||
// Подписи Y
|
||||
ctx.fillStyle = '#b0b0b0';
|
||||
ctx.font = '10px sans-serif';
|
||||
ctx.textAlign = 'right';
|
||||
for(let i=0; i<=4; i++) {
|
||||
const val = (maxY * i / 4).toFixed(0);
|
||||
const y = ch + pad.top - (ch * i / 4);
|
||||
ctx.fillText(val, pad.left - 5, y + 3);
|
||||
|
||||
// Сетка
|
||||
ctx.strokeStyle = '#2c2c2c';
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(pad.left, y);
|
||||
ctx.lineTo(cw + pad.left, y);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
// Заголовок оси Y
|
||||
ctx.save();
|
||||
ctx.translate(15, ch/2 + pad.top);
|
||||
ctx.rotate(-Math.PI/2);
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(yAxisLabel, 0, 0);
|
||||
ctx.restore();
|
||||
}
|
||||
|
||||
function drawLineChart(ctx, data, pad, cw, ch, maxY, getValueFn, color, lineWidth) {
|
||||
if (!data.length) return;
|
||||
|
||||
ctx.strokeStyle = color;
|
||||
ctx.lineWidth = lineWidth;
|
||||
ctx.beginPath();
|
||||
|
||||
data.forEach((item, index) => {
|
||||
const val = getValueFn(item);
|
||||
const x = pad.left + (index / (data.length - 1)) * cw;
|
||||
const y = pad.top + ch - (val / maxY) * ch;
|
||||
|
||||
if (index === 0) ctx.moveTo(x, y);
|
||||
else ctx.lineTo(x, y);
|
||||
|
||||
// Точка
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillRect(x-2, y-2, 4, 4);
|
||||
});
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
/**
|
||||
* Рисует график прогресса с вертикальным стеком накопительного веса
|
||||
*/
|
||||
function drawCumulativeVolumeChart(ctx, data, pad, cw, ch, maxY) {
|
||||
if (!data.length) return;
|
||||
|
||||
// 1. Сначала рисуем соединительную линию для ОБЩИХ итогов (тренд)
|
||||
ctx.strokeStyle = '#bb86fc'; // Основной цвет (например, фиолетовый)
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
|
||||
data.forEach((item, index) => {
|
||||
const x = pad.left + (index / (data.length - 1 || 1)) * cw;
|
||||
const y = pad.top + ch - (item.totalVolume / maxY) * ch;
|
||||
|
||||
if (index === 0) ctx.moveTo(x, y);
|
||||
else ctx.lineTo(x, y);
|
||||
});
|
||||
ctx.stroke();
|
||||
|
||||
// 2. Рисуем вертикальные стеки точек для каждой даты
|
||||
data.forEach((item, index) => {
|
||||
const x = pad.left + (index / (data.length - 1 || 1)) * cw;
|
||||
|
||||
item.cumulativePoints.forEach((cumWeight, pointIndex) => {
|
||||
const isLast = pointIndex === item.cumulativePoints.length - 1;
|
||||
const y = pad.top + ch - (cumWeight / maxY) * ch;
|
||||
|
||||
ctx.beginPath();
|
||||
|
||||
if (isLast) {
|
||||
// Финальная точка: крупная, непрозрачная, с белой обводкой для контраста
|
||||
ctx.fillStyle = '#bb86fc';
|
||||
ctx.arc(x, y, 5, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
|
||||
ctx.strokeStyle = '#ffffff';
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.stroke();
|
||||
} else {
|
||||
// Промежуточные точки: полупрозрачные, поменьше
|
||||
ctx.fillStyle = 'rgba(187, 134, 252, 0.4)'; // Тот же цвет, но 40% непрозрачности
|
||||
ctx.arc(x, y, 3, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
});
|
||||
|
||||
// Опционально: провести бледную вертикальную линию от 0 до итоговой точки,
|
||||
// чтобы визуально связать подходы в один "столбик"
|
||||
if (item.cumulativePoints.length > 1) {
|
||||
const bottomY = pad.top + ch; // Ось X
|
||||
const topY = pad.top + ch - (item.totalVolume / maxY) * ch;
|
||||
|
||||
ctx.strokeStyle = 'rgba(187, 134, 252, 0.15)';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x, bottomY);
|
||||
ctx.lineTo(x, topY);
|
||||
ctx.stroke();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function drawLegend(ctx, width, items) {
|
||||
ctx.font = '10px sans-serif';
|
||||
ctx.textAlign = 'left';
|
||||
let xOffset = 10;
|
||||
items.forEach(item => {
|
||||
ctx.fillStyle = item.color;
|
||||
ctx.fillRect(xOffset, 10, 10, 10);
|
||||
ctx.fillStyle = '#fff';
|
||||
ctx.fillText(item.label, xOffset + 15, 19);
|
||||
xOffset += ctx.measureText(item.label).width + 30;
|
||||
});
|
||||
}
|
||||
|
||||
function drawEmptyState(ctx, w, h, text) {
|
||||
ctx.fillStyle = '#666';
|
||||
ctx.font = '14px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
const lines = text.split('\n');
|
||||
lines.forEach((line, i) => {
|
||||
ctx.fillText(line, w/2, h/2 + (i * 20) - (lines.length*10)/2);
|
||||
});
|
||||
}
|
||||
|
||||
function formatShortDate(isoString) {
|
||||
return new Date(isoString).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit' });
|
||||
}
|
||||
Reference in New Issue
Block a user