TPTIP-95: показать меню и план на экране регистрации по введённым данным
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
92787f6b9d
commit
f690903279
2
openspec/changes/tptip-95-plan-result/.openspec.yaml
Normal file
2
openspec/changes/tptip-95-plan-result/.openspec.yaml
Normal file
@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-26
|
||||
10
openspec/changes/tptip-95-plan-result/design.md
Normal file
10
openspec/changes/tptip-95-plan-result/design.md
Normal file
@ -0,0 +1,10 @@
|
||||
## Context
|
||||
|
||||
goalPlanCard в profile/app.js показывается на экране регистрации и в профиле. Без входа он выводил только текст goalPlanMissing, расчёт делался лишь после создания учётной записи.
|
||||
|
||||
## Decisions
|
||||
|
||||
- Без входа карточка берёт значения полей формы регистрации (data-auth-form) и считает результат общей чистой функцией nutrition() из profile/nutrition.mjs — той же, что в публичной форме и на сервере. Сервер не вызывается, данные не сохраняются.
|
||||
- Проверка полей: измерения — validateMeasurement (подсказка у поля), пол/активность/цель — checkValidity; под кнопкой перечисляются тексты ошибок из errors.* — те же, что в публичной форме.
|
||||
- Изменение любого поля формы регистрации скрывает результат и сбрасывает aria-expanded, как в публичной форме (сценарий «Смена цели до повторного расчёта»).
|
||||
- Браузер в песочнице агента не запускается (нет системных библиотек), поэтому добавлен node-тест на jsdom, который загружает profile/app.js с подменой импортов и проходит путь регистрации: пустые поля → сообщение, заполненные → 4 дня, смена цели → другой результат.
|
||||
20
openspec/changes/tptip-95-plan-result/proposal.md
Normal file
20
openspec/changes/tptip-95-plan-result/proposal.md
Normal file
@ -0,0 +1,20 @@
|
||||
## Why
|
||||
|
||||
Агент приёмки на версии для проверки нажал «Создать меню и план тренировок» на экране регистрации и не увидел результата: кнопка всегда показывала только просьбу заполнить данные и создать учётную запись, даже если все поля уже заполнены. Пользователь не понимал, чего не хватает.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Кнопка «Создать меню и план тренировок» на экране регистрации рассчитывает меню и план по уже введённым данным (рост, вес, возраст, пол, активность, цель) прямо на странице, без создания учётной записи.
|
||||
- Если данных не хватает или они неверны, под кнопкой показано понятное сообщение и перечень полей, которые нужно заполнить или исправить; у полей видны подсказки.
|
||||
- При изменении данных результат скрывается до повторного нажатия, чтобы не показывать устаревший план.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
### Modified Capabilities
|
||||
- `public-menu-plan`: результат на экране регистрации и сообщение о недостающих данных.
|
||||
|
||||
## Impact
|
||||
|
||||
- profile/app.js (goalPlanCard), profile/i18n.json (ru/kk/en), браузерный сценарий goal-menu-plan, тест profile.test.mjs.
|
||||
@ -0,0 +1,25 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Результат на экране регистрации
|
||||
|
||||
На экране регистрации кнопка «Создать меню и план тренировок» SHALL показывать меню и упражнения по четырём дням, рассчитанные по уже введённым росту, весу, возрасту, полу, активности и цели, без создания учётной записи. Если данных не хватает или они неверны, приложение SHALL показывать понятное сообщение и перечень полей, которые нужно заполнить или исправить, а не пустой результат. Изменение данных SHALL скрывать прежний результат до повторного нажатия.
|
||||
|
||||
#### Scenario: Результат по введённым данным
|
||||
- **GIVEN** пользователь без входа открыл регистрацию на русском
|
||||
- **AND** указал рост 175 см, вес 75 кг, возраст 30 лет, мужской пол, лёгкую активность и похудение
|
||||
- **WHEN** он нажимает «Создать меню и план тренировок»
|
||||
- **THEN** видны четыре дня, в каждом подписанные блюда с порциями в граммах и упражнения
|
||||
- **AND** у первого упражнения показано два подхода
|
||||
|
||||
#### Scenario: Другая цель даёт другой результат
|
||||
- **GIVEN** на экране регистрации показан результат для похудения
|
||||
- **WHEN** пользователь выбирает набор массы и снова нажимает «Создать меню и план тренировок»
|
||||
- **THEN** у первого упражнения показано четыре подхода
|
||||
- **AND** порция завтрака в первом дне больше
|
||||
|
||||
#### Scenario: Не хватает данных
|
||||
- **GIVEN** пользователь без входа открыл регистрацию и оставил рост и пол пустыми
|
||||
- **WHEN** он нажимает «Создать меню и план тренировок»
|
||||
- **THEN** под кнопкой написано «Заполните возраст, рост, вес, пол, активность и цель — тогда здесь появятся меню и план по дням.»
|
||||
- **AND** перечислены «Рост не заполнен. Введите число от 100 до 250 см.» и «Пол не выбран. Выберите вариант для расчёта.»
|
||||
- **AND** дни меню и плана не показаны
|
||||
9
openspec/changes/tptip-95-plan-result/tasks.md
Normal file
9
openspec/changes/tptip-95-plan-result/tasks.md
Normal file
@ -0,0 +1,9 @@
|
||||
## 1. Результат на экране регистрации
|
||||
|
||||
- [x] 1.1 Рассчитывать меню и план по полям формы регистрации при нажатии кнопки и скрывать результат при изменении полей.
|
||||
- [x] 1.2 Показывать сообщение и перечень недостающих или неверных полей (ru/kk/en).
|
||||
|
||||
## 2. Проверки
|
||||
|
||||
- [x] 2.1 Тест на jsdom для пустых данных, результата по дням и смены цели; обновить браузерный сценарий goal-menu-plan.
|
||||
- [x] 2.2 Выполнить lint, test, build и openspec validate.
|
||||
@ -242,20 +242,54 @@ function renderPublicCalculation(calculation, container = root, welcomeFields) {
|
||||
if (calculation.result) showResult();
|
||||
}
|
||||
function goalPlanCard() {
|
||||
const content = el('div', { id: 'goal-plan-content', hidden: '' });
|
||||
const heading = el('h2', { tabindex: '-1' }, t(current ? 'goalPlanHeading' : 'createGoalPlan'));
|
||||
content.append(heading);
|
||||
if (current) appendGoalPlan(content, current.profile.goal, current.nutrition.menuByDay);
|
||||
else content.append(el('p', {}, t('goalPlanMissing')));
|
||||
const content = el('div', { id: 'goal-plan-content', hidden: '', 'aria-live': 'polite' });
|
||||
const heading = el('h2', { tabindex: '-1' }, t('goalPlanHeading'));
|
||||
function showPlan() {
|
||||
content.replaceChildren(heading);
|
||||
if (current) {
|
||||
appendGoalPlan(content, current.profile.goal, current.nutrition.menuByDay);
|
||||
return;
|
||||
}
|
||||
// Without an account the plan is calculated on this page from the registration fields.
|
||||
const form = root.querySelector('[data-auth-form]');
|
||||
const problems = [];
|
||||
for (const name of [...measurements, 'sex', 'activity', 'goal']) {
|
||||
const input = form?.elements.namedItem(name);
|
||||
if (!input) continue;
|
||||
if (measurements.includes(name)) {
|
||||
if (!validateMeasurement(input)) problems.push(measurementError(input));
|
||||
} else if (!input.checkValidity()) problems.push(errorText(name));
|
||||
}
|
||||
let result;
|
||||
if (form && !problems.length) {
|
||||
try { result = nutrition(Object.fromEntries(new FormData(form))); }
|
||||
catch (err) { problems.push(errorText(err.message)); }
|
||||
}
|
||||
if (!result) {
|
||||
content.append(el('div', { class: 'error', role: 'alert', 'data-goal-plan-missing': '' },
|
||||
el('p', {}, t('goalPlanMissing')), el('ul', {}, problems.map(text => el('li', {}, text)))));
|
||||
return;
|
||||
}
|
||||
appendGoalPlan(content, form.elements.namedItem('goal').value, result.menuByDay);
|
||||
content.append(el('p', { class: 'notice' }, t('notice')));
|
||||
}
|
||||
const button = el('button', {
|
||||
type: 'button', class: 'primary', 'aria-controls': content.id, 'aria-expanded': 'false',
|
||||
'data-goal-plan-open': '',
|
||||
onclick: () => {
|
||||
showPlan();
|
||||
content.hidden = false;
|
||||
button.setAttribute('aria-expanded', 'true');
|
||||
heading.focus();
|
||||
}
|
||||
}, t('createGoalPlan'));
|
||||
return el('section', { class: 'card' }, button, content);
|
||||
const card = el('section', { class: 'card' }, button, content);
|
||||
card.hidePlan = () => {
|
||||
content.hidden = true;
|
||||
content.replaceChildren();
|
||||
button.setAttribute('aria-expanded', 'false');
|
||||
};
|
||||
return card;
|
||||
}
|
||||
function render() {
|
||||
document.documentElement.lang=lang;document.title=t('app');
|
||||
@ -291,13 +325,15 @@ function render() {
|
||||
if (planOpen && !current) { renderPublicPlan(); return; }
|
||||
root.append(planCard());
|
||||
if (!current && mode === 'login') root.append(publicCalculationButton());
|
||||
if (current || mode === 'register') root.append(goalPlanCard());
|
||||
const planResult = current || mode === 'register' ? goalPlanCard() : null;
|
||||
if (planResult) root.append(planResult);
|
||||
const error = el('p',{class:'error',role:'alert','aria-live':'polite'},message);
|
||||
const inputs = el('div',{class:'grid'},
|
||||
!current?field('username',{hint:'usernameHint'}):null,!current?field('password',{type:'password',hint:'passwordHint'}):null,
|
||||
...(current || mode==='register' ? profileFields() : []));
|
||||
const submit = el('button',{class:'primary',type:'submit'},t(current?'save':mode));
|
||||
const form = el('form',{class:'card',novalidate:''},!current?el('p',{class:'hint','data-auth-guidance':''},t('authGuidance')):null,inputs,error,el('div',{class:'actions'},submit));
|
||||
const form = el('form',{class:'card',novalidate:'','data-auth-form':''},!current?el('p',{class:'hint','data-auth-guidance':''},t('authGuidance')):null,inputs,error,el('div',{class:'actions'},submit));
|
||||
if (planResult && !current) form.addEventListener('input',()=>planResult.hidePlan());
|
||||
form.addEventListener('submit',async e=>{
|
||||
e.preventDefault();
|
||||
if (!validateForm(form, error)) return;
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
"publicPlanIntro": "Укажите данные о себе, чтобы рассчитать порции и подобрать число подходов по вашей цели. Расчёт выполняется на этой странице.",
|
||||
"welcomeCalculationIntro": "Заполните поля, чтобы получить меню и план без входа.",
|
||||
"publicPlanBack": "Назад",
|
||||
"goalPlanMissing": "Заполните возраст, рост, вес, пол, активность и цель. Создайте учётную запись, чтобы увидеть меню и план.",
|
||||
"goalPlanMissing": "Заполните возраст, рост, вес, пол, активность и цель — тогда здесь появятся меню и план по дням.",
|
||||
"goalPlanMenuHint": "Пример меню на каждый день. Порции рассчитаны для вашей цели.",
|
||||
"goalPlanDose": "{sets} × {reps} (подходы × повторения)",
|
||||
"goalPlanMeals": "Пример меню",
|
||||
@ -103,7 +103,7 @@
|
||||
"publicPlanIntro": "Мақсатыңызға сай порциялар мен жаттығу тәсілдерінің санын есептеу үшін өзіңіз туралы деректерді енгізіңіз. Есеп осы бетте жасалады.",
|
||||
"welcomeCalculationIntro": "Кірмей-ақ мәзір мен жоспар алу үшін өрістерді толтырыңыз.",
|
||||
"publicPlanBack": "Артқа",
|
||||
"goalPlanMissing": "Жасыңызды, бойыңызды, салмағыңызды, жынысыңызды, белсенділігіңізді және мақсатыңызды көрсетіңіз. Мәзір мен жоспарды көру үшін есептік жазба жасаңыз.",
|
||||
"goalPlanMissing": "Жасыңызды, бойыңызды, салмағыңызды, жынысыңызды, белсенділігіңізді және мақсатыңызды көрсетіңіз — сонда мұнда күндер бойынша мәзір мен жоспар шығады.",
|
||||
"goalPlanMenuHint": "Күн сайынғы мәзір үлгісі. Үлес мөлшері мақсатыңызға сай есептелген.",
|
||||
"goalPlanDose": "{sets} × {reps} (тәсілдер × қайталаулар)",
|
||||
"goalPlanMeals": "Мәзір үлгісі",
|
||||
@ -201,7 +201,7 @@
|
||||
"publicPlanIntro": "Enter your details to calculate meal portions and workout sets for your goal. The calculation runs on this page.",
|
||||
"welcomeCalculationIntro": "Fill in the fields to get a menu and workout plan without signing in.",
|
||||
"publicPlanBack": "Back",
|
||||
"goalPlanMissing": "Enter your age, height, weight, sex, activity level and goal. Create an account to see your meal and workout plan.",
|
||||
"goalPlanMissing": "Enter your age, height, weight, sex, activity level and goal, and your day-by-day meal and workout plan will appear here.",
|
||||
"goalPlanMenuHint": "Sample menu for each day. Portions are calculated for your goal.",
|
||||
"goalPlanDose": "{sets} × {reps} (sets × reps)",
|
||||
"goalPlanMeals": "Sample menu",
|
||||
|
||||
@ -15,6 +15,9 @@ test('Меню и упражнения по дням обновляются по
|
||||
await page.locator('#field-sex').selectOption('male');
|
||||
await page.locator('#field-activity').selectOption('1.375');
|
||||
await page.locator('#field-goal').selectOption('lose');
|
||||
await createPlan.click();
|
||||
await expect(page.locator('[data-goal-plan-day]')).toHaveCount(4);
|
||||
await expect(page.locator('[data-goal-plan-day]').first()).toContainText('2 × 10');
|
||||
await page.locator('button[type=submit]').click();
|
||||
await expect(page.locator('#field-password')).toHaveCount(0);
|
||||
await createPlan.click();
|
||||
|
||||
90
tests/registration-plan.test.mjs
Normal file
90
tests/registration-plan.test.mjs
Normal file
@ -0,0 +1,90 @@
|
||||
// TPTIP-95: кнопка «Создать меню и план тренировок» на экране регистрации показывает результат по дням.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { nutrition } from '../profile/nutrition.mjs';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const GymPlan = require('../gym-plan.i18n.js');
|
||||
const translations = JSON.parse(readFileSync(new URL('../profile/i18n.json', import.meta.url), 'utf8'));
|
||||
// The module imports are replaced with globals so that jsdom can run the page script.
|
||||
const appSource = readFileSync(new URL('../profile/app.js', import.meta.url), 'utf8')
|
||||
.replace(/^import .*$/gm, '');
|
||||
|
||||
async function openRegistration() {
|
||||
const dom = new JSDOM('<!doctype html><html><body><main id="app"></main></body></html>', {
|
||||
url: 'http://localhost/?lang=ru', runScripts: 'outside-only', pretendToBeVisual: true,
|
||||
});
|
||||
const w = dom.window;
|
||||
Object.assign(w, {
|
||||
GymPlan, nutrition, initTelemetry: async () => {}, scrollTo: () => {},
|
||||
fetch: async path => path === '/profile/i18n.json'
|
||||
? { ok: true, json: async () => translations }
|
||||
: { ok: false, status: 401, json: async () => ({ error: 'signin' }) },
|
||||
});
|
||||
w.sessionStorage.setItem('tpt.welcomeSeen', '1');
|
||||
w.eval(`window.__ready = (async () => {\n${appSource}\n})();`);
|
||||
await w.__ready;
|
||||
const document = w.document;
|
||||
const toRegister = [...document.querySelectorAll('button')].find(b => b.textContent === translations.ru.toRegister);
|
||||
toRegister.click();
|
||||
return { w, document };
|
||||
}
|
||||
|
||||
function fill(w, document, values) {
|
||||
for (const [name, value] of Object.entries(values)) {
|
||||
const input = document.querySelector(`[data-auth-form] [name=${name}]`);
|
||||
input.value = value;
|
||||
input.dispatchEvent(new w.Event('input', { bubbles: true }));
|
||||
}
|
||||
}
|
||||
const openPlan = document => document.querySelector('[data-goal-plan-open]').click();
|
||||
const days = document => [...document.querySelectorAll('#goal-plan-content [data-goal-plan-day]')];
|
||||
const measurements = { height: '175', weight: '75', age: '30', sex: 'male', activity: '1.375' };
|
||||
|
||||
test('Не хватает данных: сообщение и перечень полей вместо пустого результата', async () => {
|
||||
const { w, document } = await openRegistration();
|
||||
fill(w, document, { weight: '75', age: '30', activity: '1.375' });
|
||||
openPlan(document);
|
||||
const content = document.querySelector('#goal-plan-content');
|
||||
assert.equal(content.hidden, false);
|
||||
const missing = content.querySelector('[data-goal-plan-missing]').textContent;
|
||||
assert.match(missing, /Заполните возраст, рост, вес, пол, активность и цель — тогда здесь появятся меню и план по дням\./);
|
||||
assert.match(missing, /Рост не заполнен\. Введите число от 100 до 250 см\./);
|
||||
assert.match(missing, /Пол не выбран\. Выберите вариант для расчёта\./);
|
||||
assert.doesNotMatch(missing, /Вес|Возраст не/);
|
||||
assert.equal(days(document).length, 0);
|
||||
});
|
||||
|
||||
test('Результат по введённым данным: четыре дня с блюдами и упражнениями', async () => {
|
||||
const { w, document } = await openRegistration();
|
||||
fill(w, document, { ...measurements, goal: 'lose' });
|
||||
openPlan(document);
|
||||
const list = days(document);
|
||||
assert.equal(list.length, 4);
|
||||
for (const day of list) {
|
||||
assert.match(day.textContent, /Пример меню/);
|
||||
assert.match(day.textContent, /Упражнения/);
|
||||
assert.match(day.textContent, /\d+ г/);
|
||||
}
|
||||
assert.match(list[0].textContent, /Жим гантелей лёжа — 2 × 10/);
|
||||
assert.equal(document.querySelector('[data-goal-plan-missing]'), null);
|
||||
});
|
||||
|
||||
test('Другая цель даёт другой результат, а изменение данных скрывает прежний', async () => {
|
||||
const { w, document } = await openRegistration();
|
||||
fill(w, document, { ...measurements, goal: 'lose' });
|
||||
openPlan(document);
|
||||
const before = days(document).map(day => day.textContent);
|
||||
fill(w, document, { goal: 'gain' });
|
||||
assert.equal(document.querySelector('#goal-plan-content').hidden, true);
|
||||
openPlan(document);
|
||||
const after = days(document).map(day => day.textContent);
|
||||
assert.equal(after.length, 4);
|
||||
assert.match(after[0], /Жим гантелей лёжа — 4 × 10/);
|
||||
const breakfast = text => Number(text.match(/овсянка с йогуртом[^·]*· (\d+)/)[1]);
|
||||
assert.ok(breakfast(after[0]) > breakfast(before[0]));
|
||||
assert.notDeepEqual(after, before);
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user