Merge pull request 'TPTIP-89: расчёт меню и плана тренировок до входа' (#84) from task/tptip-89 into main
This commit is contained in:
commit
aa0de42e7d
@ -5,6 +5,7 @@
|
||||
- TPTIP-3: npm ci; npm run build; npm start; проверки npm run lint и npm test, браузер npx playwright install chromium && npx playwright test. Каталог /recipes.html, ru/kk/en, локальные фото assets/. При объединении сохраняйте маршруты каталога и сборку telemetry.
|
||||
|
||||
## Решения
|
||||
- TPTIP-89: чистый расчёт в profile/nutrition.mjs общий для сервера и публичной формы, которая держит данные в памяти страницы. Проверка: tests/browser/public-menu-plan.spec.js.
|
||||
- TPTIP-88: goalPlanCard показывает четыре дня из GymPlan, порции из nutrition.menu и подходы из setsByGoal. Проверка: tests/browser/goal-menu-plan.spec.js.
|
||||
- TPTIP-60: публичное приветствие profile/app.js показывает #welcome-goal и [data-goal-note], шаблон GymPlan.welcomeGoal; tests/browser/welcome-goal.spec.js проверяет ru/kk/en на 360×640 и 1440×900.
|
||||
- TPTIP-31: recipeView использует recipePhoto с заглушкой при пустом/SVG/ошибочном фото; локальные фото b1/b3/b6, составы и подписи — GymPlan.text('ru').recipeDetails (ru/kk/en). CACHE tpt-v12-recipe-details; изменённые пользовательские составы не перезаписывать.
|
||||
@ -20,8 +21,6 @@
|
||||
- TPTIP-14: подсказки диапазонов в мастере — hint в numField (calcFields); подписи колец в ring(...) 'г белка'/'мл воды'; кнопку «Далее» не переименовывать (тесты ищут по тексту).
|
||||
- TPTIP-16: сообщения об ошибках мастера строятся в numField по параметру what ('возраст'/'рост'/'вес') и hint; локальная main бывает устаревшей — ветку делайте от origin/main.
|
||||
- TPTIP-20: chooseRecipe(r, confirmed) спрашивает подтверждение, если блюдо уже выбрано на эту дату; тост «<Блюдо> добавлен в приём пищи».
|
||||
- TPTIP-21: мастер (шаг 1→2→«Готово», onboarded, кольца с «ккал/г белка/мл воды») проверен — код менять не пришлось, закреплено тестом в tests/wizard.test.js.
|
||||
- TPTIP-24: шаг 2 мастера (нормы, «Назад», «Готово») уже работал — закреплено тестом в tests/wizard.test.js; код менять не пришлось.
|
||||
- TPTIP-25: карточка блюда (recipeView) — grid: .main (data-time/data-portion/data-macros отдельными div), .dish-body (состав+шаги на всю ширину), .dish-actions; над кольцами data-rings-caption «Съедено из дневной нормы», у ring aria-label; CACHE tpt-v8-dish-card. Скриншоты: playwright с executablePath из ~/Library/Caches/ms-playwright/chromium_headless_shell-1255.
|
||||
- TPTIP-26: тексты ошибок мастера строит wizardError(o, raw, err) в numField (поля с what): «Укажите/Проверьте <what>: … Введите число <hint>.»; нормы второго шага (normFields) тоже с what/hint и читают все поля; focusFirstError(body) на «Далее»/«Готово»; CACHE tpt-v9-wizard-errors.
|
||||
- TPTIP-27: рецепт в recipeView раскрывается кнопкой [data-recipe-toggle] (ol[data-steps] hidden), без шагов — [data-no-recipe]; CACHE tpt-v10-recipe-steps.
|
||||
@ -74,6 +73,5 @@
|
||||
- TPTIP-59: auth-form закрепляет действия входа/регистрации снизу на телефоне; planCard остаётся сверху (TPTIP-55). authGuidance ru/kk/en; tests/browser/auth-guidance.spec.js — 360×640.
|
||||
- TPTIP-61: русский первый экран уже в main (TPTIP-53/56/57); return-visit-language.spec.js проверяет EN/RU после закрытия контекста через storageState без sessionStorage.
|
||||
|
||||
- TPTIP-63: tests/browser/russian-browser-auth.spec.js проверяет ru-RU, русские подсказки, EN→RU и reload без моков; перевод уже в main.
|
||||
- TPTIP-65: ошибки credentials при login отображаются через loginCredentials (ru/kk/en); регистрация сохраняет общий credentials. tests/browser/password-guidance.spec.js проверяет реальные неверный пароль и неизвестное имя.
|
||||
- TPTIP-1: блюдо дня зависит от даты; для теста с фото выбирайте овсянку через «+ Рецепт».
|
||||
|
||||
@ -69,3 +69,5 @@
|
||||
| Меню и упражнения по цели | Создать меню и план тренировок, Меню и план тренировок, Пример меню на каждый день, подходы, повторения | генерация, сет | Результат в профиле. До расчёта указываем, какие данные нужно заполнить |
|
||||
|
||||
| Экран дневника за день | Сегодня, + Еда, + Тренировка, + Вода | — | Вкладка открывает выбранный день. Кнопка воды добавляет 250 мл |
|
||||
|
||||
| Расчёт до входа | Выберите цель, Создать меню и план тренировок, Назад | — | Возраст, рост, вес, пол для расчёта, активность и цель используются на открытой странице |
|
||||
|
||||
@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-25
|
||||
@ -0,0 +1,15 @@
|
||||
# Design
|
||||
|
||||
## Context
|
||||
|
||||
Расчёт для профиля и проверка измерений находятся в серверном модуле. Карточка профиля уже показывает меню и упражнения по цели.
|
||||
|
||||
## Decisions
|
||||
|
||||
- Открывать форму из приветствия и экрана входа. Переносить выбранную на приветствии цель и давать изменить её в форме.
|
||||
- Вынести чистый расчёт с проверкой данных в общий модуль для браузера и сервера. Значения формы и результат держать в памяти страницы, расчёт выполняется на устройстве пользователя.
|
||||
- Использовать существующие поля, упражнения, порции и переводы. После редактирования нужно нажать кнопку расчёта снова.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
Общий модуль должен отдаваться основным сервером. Проверка браузером проходит через входную страницу настоящего сервера.
|
||||
@ -0,0 +1,27 @@
|
||||
# Proposal
|
||||
|
||||
[TPTIP-89](https://peppa.telecom.quest) — дать пользователю рассчитать меню и план тренировок до входа.
|
||||
|
||||
## Why
|
||||
|
||||
На первом экране можно выбрать цель, но расчёт доступен только после создания учётной записи.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Добавить кнопку «Создать меню и план тренировок» на приветствии и экране входа.
|
||||
- Открывать отдельную форму с возрастом, ростом, весом, полом для расчёта, активностью и целью.
|
||||
- После заполнения показывать пример меню с порциями и четыре дня тренировок.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- `public-menu-plan` — расчёт меню и плана тренировок без входа.
|
||||
|
||||
## Impact
|
||||
|
||||
Публичный экран, переводы, общий расчёт питания и браузерная проверка. Создание учётной записи и сохранение плана вне задачи.
|
||||
|
||||
## Открытые вопросы
|
||||
|
||||
Нет.
|
||||
@ -0,0 +1,22 @@
|
||||
## Purpose
|
||||
|
||||
Дать пользователям возможность получить пример меню и план тренировок до входа.
|
||||
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Расчёт меню и плана без входа
|
||||
|
||||
Приложение SHALL показывать кнопку «Создать меню и план тренировок» до входа и давать по ней рассчитать меню и план по возрасту, росту, весу, полу для расчёта, активности и цели без учётной записи.
|
||||
|
||||
#### Scenario: Расчёт с приветствия
|
||||
- **GIVEN** пользователь без учётной записи открыл приветствие на русском
|
||||
- **AND** по кнопке «Создать меню и план тренировок» ввёл возраст 30 лет, рост 175 см, вес 75 кг, выбрал мужской пол, лёгкую активность и похудение
|
||||
- **WHEN** пользователь нажимает «Создать меню и план тренировок» в форме
|
||||
- **THEN** видны порции блюд и четыре дня тренировок
|
||||
- **AND** первое упражнение показано с двумя подходами
|
||||
|
||||
#### Scenario: Рост вне диапазона
|
||||
- **GIVEN** пользователь без входа открыл форму и указал рост 5 см
|
||||
- **WHEN** он нажимает «Создать меню и план тренировок»
|
||||
- **THEN** у поля роста видна подсказка о допустимом диапазоне от 100 до 250 см
|
||||
- **AND** результат не показан
|
||||
@ -0,0 +1,8 @@
|
||||
## 1. Форма и расчёт
|
||||
|
||||
- [x] 1.1 Открыть публичную форму из приветствия и экрана входа, добавить тексты на русском, казахском и английском.
|
||||
- [x] 1.2 Подключить общий расчёт и показать порции и четыре дня тренировок.
|
||||
|
||||
## 2. Проверка
|
||||
|
||||
- [x] 2.1 Проверить в браузере расчёт и ошибку ввода до входа, запустить проверки проекта и `openspec validate`.
|
||||
23
openspec/specs/public-menu-plan/spec.md
Normal file
23
openspec/specs/public-menu-plan/spec.md
Normal file
@ -0,0 +1,23 @@
|
||||
# public-menu-plan Specification
|
||||
|
||||
## Purpose
|
||||
Дать пользователям возможность получить пример меню и план тренировок до входа.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Расчёт меню и плана без входа
|
||||
|
||||
Приложение SHALL показывать кнопку «Создать меню и план тренировок» до входа и давать по ней рассчитать меню и план по возрасту, росту, весу, полу для расчёта, активности и цели без учётной записи.
|
||||
|
||||
#### Scenario: Расчёт с приветствия
|
||||
- **GIVEN** пользователь без учётной записи открыл приветствие на русском
|
||||
- **AND** по кнопке «Создать меню и план тренировок» ввёл возраст 30 лет, рост 175 см, вес 75 кг, выбрал мужской пол, лёгкую активность и похудение
|
||||
- **WHEN** пользователь нажимает «Создать меню и план тренировок» в форме
|
||||
- **THEN** видны порции блюд и четыре дня тренировок
|
||||
- **AND** первое упражнение показано с двумя подходами
|
||||
|
||||
#### Scenario: Рост вне диапазона
|
||||
- **GIVEN** пользователь без входа открыл форму и указал рост 5 см
|
||||
- **WHEN** он нажимает «Создать меню и план тренировок»
|
||||
- **THEN** у поля роста видна подсказка о допустимом диапазоне от 100 до 250 см
|
||||
- **AND** результат не показан
|
||||
@ -8,7 +8,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { ProfileService, InputError } from './profile/service.mjs';
|
||||
if (process.env.SENTRY_DSN) Sentry.init({dsn:process.env.SENTRY_DSN,release:process.env.SENTRY_RELEASE,environment:process.env.SENTRY_ENVIRONMENT || 'dev',sendDefaultPii:false,beforeSend(event){ delete event.request; delete event.user; return event; }});
|
||||
const root = fileURLToPath(new URL('.',import.meta.url));
|
||||
const files = new Map([["/recipes.html", ["recipes.html", "text/html"]],["/recipes.css", ["recipes.css", "text/css"]],["/telemetry.js", ["generated/telemetry.js", "text/javascript"]],["/recipes.js", ["recipes.js", "text/javascript"]],["/recipes-core.js", ["recipes-core.js", "text/javascript"]],["/recipes.data.json", ["recipes.data.json", "application/json"]],["/recipes.i18n.json", ["recipes.i18n.json", "application/json"]],["/recipes-status.i18n.js", ["recipes-status.i18n.js", "text/javascript"]],["/assets/oats.jpg", ["assets/oats.jpg", "image/jpeg"]],["/assets/chicken.jpg", ["assets/chicken.jpg", "image/jpeg"]],["/assets/salad.jpg", ["assets/salad.jpg", "image/jpeg"]],['/profile/tracker-guard.js',['profile/tracker-guard.js','text/javascript']],['/gym-plan.i18n.js',['gym-plan.i18n.js','text/javascript']],['/manifest.webmanifest',['manifest.webmanifest','application/manifest+json']],['/sw.js',['profile/private-sw.js','text/javascript']],['/icon.svg',['icon.svg','image/svg+xml']],['/',['profile/index.html','text/html']],['/profile/app.js',['profile/app.js','text/javascript']],['/profile/telemetry.js',['profile/telemetry.js','text/javascript']],['/profile/style.css',['profile/style.css','text/css']],['/profile/i18n.json',['profile/i18n.json','application/json']]]);
|
||||
const files = new Map([['/profile/nutrition.mjs',['profile/nutrition.mjs','text/javascript']],["/recipes.html", ["recipes.html", "text/html"]],["/recipes.css", ["recipes.css", "text/css"]],["/telemetry.js", ["generated/telemetry.js", "text/javascript"]],["/recipes.js", ["recipes.js", "text/javascript"]],["/recipes-core.js", ["recipes-core.js", "text/javascript"]],["/recipes.data.json", ["recipes.data.json", "application/json"]],["/recipes.i18n.json", ["recipes.i18n.json", "application/json"]],["/recipes-status.i18n.js", ["recipes-status.i18n.js", "text/javascript"]],["/assets/oats.jpg", ["assets/oats.jpg", "image/jpeg"]],["/assets/chicken.jpg", ["assets/chicken.jpg", "image/jpeg"]],["/assets/salad.jpg", ["assets/salad.jpg", "image/jpeg"]],['/profile/tracker-guard.js',['profile/tracker-guard.js','text/javascript']],['/gym-plan.i18n.js',['gym-plan.i18n.js','text/javascript']],['/manifest.webmanifest',['manifest.webmanifest','application/manifest+json']],['/sw.js',['profile/private-sw.js','text/javascript']],['/icon.svg',['icon.svg','image/svg+xml']],['/',['profile/index.html','text/html']],['/profile/app.js',['profile/app.js','text/javascript']],['/profile/telemetry.js',['profile/telemetry.js','text/javascript']],['/profile/style.css',['profile/style.css','text/css']],['/profile/i18n.json',['profile/i18n.json','application/json']]]);
|
||||
export function createApp({database,secure = process.env.NODE_ENV === 'production'} = {}) {
|
||||
if (!database) mkdirSync(process.env.DATA_DIR || resolve(root,'data'),{recursive:true,mode:0o700});
|
||||
const service = new ProfileService(database || resolve(process.env.DATA_DIR || resolve(root,'data'),'profile.sqlite'));
|
||||
|
||||
155
profile/app.js
155
profile/app.js
@ -1,4 +1,5 @@
|
||||
/* global GymPlan */
|
||||
import { nutrition } from '/profile/nutrition.mjs';
|
||||
import { initTelemetry } from '/profile/telemetry.js';
|
||||
initTelemetry().catch(() => {});
|
||||
const translations = await fetch('/profile/i18n.json').then(r=>r.json());
|
||||
@ -30,6 +31,7 @@ function saveLanguage() {
|
||||
if (supportedLanguage(requestedLanguage)) saveLanguage();
|
||||
let current, mode = 'login', message = '', planOpen = false;
|
||||
let welcomeGoal = 'maintain';
|
||||
let publicCalculation;
|
||||
const setsByGoal = { lose: 2, maintain: 3, gain: 4 };
|
||||
const goalOptions = [['lose','goalLose'],['maintain','goalMaintain'],['gain','goalGain']];
|
||||
let welcome = true;
|
||||
@ -72,10 +74,10 @@ function validateMeasurement(input) {
|
||||
showFieldError(input,valid ? '' : errorText(key));
|
||||
return valid;
|
||||
}
|
||||
function field(key,{type='text',min,max,hint}={}) {
|
||||
function field(key,{type='text',min,max,hint,value=current?.profile[key] ?? ''}={}) {
|
||||
const id = 'field-'+key;
|
||||
const measurement = measurements.includes(key);
|
||||
const input = el('input',{id,name:key,type,required:'',value:current?.profile[key] ?? '',...(min ? {min,max,step:key==='age'?'1':'any'} : {}),...(key==='username'?{autocomplete:'username',pattern:'[a-zA-Z0-9_-]{3,40}',minlength:3,maxlength:40}:{}),...(key==='password'?{autocomplete:mode==='register'?'new-password':'current-password',minlength:12,maxlength:128}:{}),...((hint || measurement)?{'aria-describedby':[hint?id+'-hint':null,measurement?id+'-error':null].filter(Boolean).join(' ')}:{})});
|
||||
const input = el('input',{id,name:key,type,required:'',value,...(min ? {min,max,step:key==='age'?'1':'any'} : {}),...(key==='username'?{autocomplete:'username',pattern:'[a-zA-Z0-9_-]{3,40}',minlength:3,maxlength:40}:{}),...(key==='password'?{autocomplete:mode==='register'?'new-password':'current-password',minlength:12,maxlength:128}:{}),...((hint || measurement)?{'aria-describedby':[hint?id+'-hint':null,measurement?id+'-error':null].filter(Boolean).join(' ')}:{})});
|
||||
if (measurement) {
|
||||
const invalidCharacters = value => /[^0-9.,]/u.test(value);
|
||||
input.addEventListener('keydown', event => {
|
||||
@ -92,9 +94,9 @@ function field(key,{type='text',min,max,hint}={}) {
|
||||
}
|
||||
return el('label',{for:id},t(key),input,hint?el('span',{id:id+'-hint',class:'hint'},t(hint)):null,measurement?el('span',{id:id+'-error',class:'field-error',hidden:'','aria-live':'polite'}):null);
|
||||
}
|
||||
function select(key,options) {
|
||||
function select(key,options,value=current?.profile[key] ?? (key==='goal' ? welcomeGoal : '')) {
|
||||
const node = el('select',{id:'field-'+key,name:key,required:'',...(key==='sex'?{'aria-describedby':'field-sex-hint'}:{})},key==='goal'?null:el('option',{value:''},t(key+'Choose')),options.map(([value,label])=>el('option',{value},t(label))));
|
||||
node.value = current?.profile[key] ?? (key==='goal' ? welcomeGoal : '');
|
||||
node.value = value;
|
||||
return el('label',{for:'field-'+key},t(key),node,key==='sex'?el('span',{id:'field-sex-hint',class:'hint'},t('sexHint')):null);
|
||||
}
|
||||
function openPlan() {
|
||||
@ -127,25 +129,116 @@ function renderPublicPlan() {
|
||||
root.querySelector('#field-username').focus();
|
||||
}},text.record))));
|
||||
}
|
||||
function profileFields(values) {
|
||||
return [
|
||||
field('height',{type:'number',min:100,max:250,hint:'heightHint',value:values?.height}),
|
||||
field('weight',{type:'number',min:25,max:350,hint:'weightHint',value:values?.weight}),
|
||||
field('age',{type:'number',min:18,max:100,hint:'ageHint',value:values?.age}),
|
||||
select('sex',[['male','male'],['female','female']],values?.sex),
|
||||
select('activity',[['1.2','sedentary'],['1.375','light'],['1.55','moderate'],['1.725','high']],values?.activity),
|
||||
select('goal',goalOptions,values?.goal)
|
||||
];
|
||||
}
|
||||
function appendGoalPlan(content, goal, menu) {
|
||||
const goalLabel = goalOptions.find(([value]) => value === goal)[1];
|
||||
content.append(el('p', {}, t('goal') + ' — ' + t(goalLabel)), el('p', {}, t('goalPlanMenuHint')));
|
||||
for (const day of GymPlan.days(lang)) {
|
||||
content.append(el('section', { 'data-goal-plan-day': '' },
|
||||
el('h3', {}, day.name),
|
||||
el('ul', {}, menu.map(meal =>
|
||||
el('li', {}, `${t(meal.name)} · ${meal.grams} ${t('grams')}`))),
|
||||
el('ul', {}, day.exercises.map(exercise => el('li', {},
|
||||
exercise.name + ' — ' + t('goalPlanDose').replace('{sets}', setsByGoal[goal]).replace('{reps}', exercise.reps))))));
|
||||
}
|
||||
}
|
||||
function validateForm(form, error) {
|
||||
error.textContent = '';
|
||||
let firstInvalid;
|
||||
for (const input of form.querySelectorAll('input,select')) {
|
||||
const measurement = measurements.includes(input.name);
|
||||
const valid = measurement ? validateMeasurement(input) : input.checkValidity();
|
||||
if (!valid) {
|
||||
firstInvalid ||= input;
|
||||
if (!measurement && !error.textContent) error.textContent = errorText(input.name);
|
||||
}
|
||||
}
|
||||
firstInvalid?.focus();
|
||||
return !firstInvalid;
|
||||
}
|
||||
function publicCalculationButton() {
|
||||
return el('button', {
|
||||
type: 'button', class: 'primary', 'data-public-calculation': '',
|
||||
onclick: () => {
|
||||
publicCalculation = { values: { goal: welcomeGoal } };
|
||||
render();
|
||||
window.scrollTo(0, 0);
|
||||
root.querySelector('h1').focus();
|
||||
}
|
||||
}, t('createGoalPlan'));
|
||||
}
|
||||
function renderPublicCalculation() {
|
||||
const heading = root.querySelector('h1');
|
||||
heading.textContent = t('goalPlanHeading');
|
||||
heading.tabIndex = -1;
|
||||
root.querySelector('p').textContent = t('publicPlanIntro');
|
||||
const back = el('button', {
|
||||
type: 'button',
|
||||
onclick: () => {
|
||||
publicCalculation = undefined;
|
||||
render();
|
||||
root.querySelector('[data-public-calculation]').focus();
|
||||
}
|
||||
}, t('publicPlanBack'));
|
||||
const error = el('p', { class: 'error', role: 'alert', hidden: '' });
|
||||
const result = el('section', { class: 'card', hidden: '' });
|
||||
const form = el('form', { class: 'card', novalidate: '' },
|
||||
el('div', { class: 'grid' }, profileFields(publicCalculation.values)), error,
|
||||
el('div', { class: 'actions' }, el('button', { type: 'submit', class: 'primary' }, t('createGoalPlan'))));
|
||||
function showResult() {
|
||||
const title = el('h2', { tabindex: '-1' }, t('goalPlanHeading'));
|
||||
result.replaceChildren(title);
|
||||
appendGoalPlan(result, publicCalculation.values.goal, publicCalculation.result.menu);
|
||||
result.append(el('p', { class: 'notice' }, t('notice')));
|
||||
result.hidden = false;
|
||||
return title;
|
||||
}
|
||||
form.addEventListener('input', () => {
|
||||
publicCalculation.values = Object.fromEntries(new FormData(form));
|
||||
publicCalculation.result = undefined;
|
||||
result.hidden = true;
|
||||
result.replaceChildren();
|
||||
error.hidden = true;
|
||||
});
|
||||
form.addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
error.hidden = false;
|
||||
const valid = validateForm(form, error);
|
||||
error.hidden = !error.textContent;
|
||||
if (!valid) return;
|
||||
const values = Object.fromEntries(new FormData(form));
|
||||
try {
|
||||
publicCalculation.result = nutrition(values);
|
||||
publicCalculation.values = values;
|
||||
showResult().focus();
|
||||
} catch (err) {
|
||||
const input = form.elements.namedItem(err.message);
|
||||
if (measurements.includes(err.message)) showFieldError(input, errorText(err.message));
|
||||
else {
|
||||
error.textContent = errorText(err.message);
|
||||
error.hidden = false;
|
||||
}
|
||||
input?.focus();
|
||||
}
|
||||
});
|
||||
root.append(back, form, result);
|
||||
if (publicCalculation.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) {
|
||||
const goal = current.profile.goal;
|
||||
const goalLabel = goalOptions.find(([value]) => value === goal)[1];
|
||||
content.append(el('p', {}, t('goal') + ' — ' + t(goalLabel)), el('p', {}, t('goalPlanMenuHint')));
|
||||
for (const day of GymPlan.days(lang)) {
|
||||
content.append(el('section', { 'data-goal-plan-day': '' },
|
||||
el('h3', {}, day.name),
|
||||
el('ul', {}, current.nutrition.menu.map(meal =>
|
||||
el('li', {}, `${t(meal.name)} · ${meal.grams} ${t('grams')}`))),
|
||||
el('ul', {}, day.exercises.map(exercise => el('li', {},
|
||||
exercise.name + ' — ' + t('goalPlanDose').replace('{sets}', setsByGoal[goal]).replace('{reps}', exercise.reps))))));
|
||||
}
|
||||
} else {
|
||||
content.append(el('p', {}, t('goalPlanMissing')));
|
||||
}
|
||||
if (current) appendGoalPlan(content, current.profile.goal, current.nutrition.menu);
|
||||
else content.append(el('p', {}, t('goalPlanMissing')));
|
||||
const button = el('button', {
|
||||
type: 'button', class: 'primary', 'aria-controls': content.id, 'aria-expanded': 'false',
|
||||
onclick: () => {
|
||||
@ -158,11 +251,13 @@ function goalPlanCard() {
|
||||
}
|
||||
function render() {
|
||||
document.documentElement.lang=lang;document.title=t('app');
|
||||
root.classList.toggle('auth-login', !current && !welcome && mode==='login');
|
||||
root.classList.toggle('auth-form', !current && !welcome && !planOpen);
|
||||
root.classList.toggle('welcome-screen', !current && welcome && !publicCalculation);
|
||||
root.classList.toggle('auth-login', !current && !welcome && !publicCalculation && mode==='login');
|
||||
root.classList.toggle('auth-form', !current && !welcome && !planOpen && !publicCalculation);
|
||||
const language = el('select',{class:'lang','aria-label':t('language'),onchange:e=>{lang=e.target.value;saveLanguage();const url=new URL(location.href);url.searchParams.set('lang',lang);history.replaceState(null,'',url);message='';render();}},...['ru','kk','en'].map(code=>el('option',{value:code},code.toUpperCase())));
|
||||
language.value=lang;
|
||||
root.replaceChildren(el('header',{},el('span',{class:'eyebrow'},t('brand')),language),el('h1',{},current?t('profile'):t(mode+'Heading')),el('p',{},current?t('next'):t(mode+'Intro')));
|
||||
if (!current && publicCalculation) { renderPublicCalculation(); return; }
|
||||
if (!current && welcome) {
|
||||
root.querySelector('h1').textContent=t('welcomeHeading');
|
||||
root.querySelector('p').textContent=t('welcomeIntro');
|
||||
@ -178,32 +273,22 @@ function render() {
|
||||
el('label',{for:'welcome-goal'},t('goal'),goalSelect),goalNote,
|
||||
el('div',{class:'actions'},
|
||||
el('button',{type:'button','data-welcome-skip':'',onclick:()=>closeWelcome('login')},t('welcomeSkip')),
|
||||
el('button',{type:'button',class:'primary','data-welcome-next':'',onclick:()=>closeWelcome('register')},t('welcomeNext')))));
|
||||
el('button',{type:'button',class:'primary','data-welcome-next':'',onclick:()=>closeWelcome('register')},t('welcomeNext'))),publicCalculationButton()));
|
||||
return;
|
||||
}
|
||||
if (planOpen && !current) { renderPublicPlan(); return; }
|
||||
root.append(planCard());
|
||||
if (!current && mode === 'login') root.append(publicCalculationButton());
|
||||
if (current || mode === 'register') root.append(goalPlanCard());
|
||||
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' ? [field('height',{type:'number',min:100,max:250,hint:'heightHint'}),field('weight',{type:'number',min:25,max:350,hint:'weightHint'}),field('age',{type:'number',min:18,max:100,hint:'ageHint'}),
|
||||
select('sex',[['male','male'],['female','female']]),select('activity',[['1.2','sedentary'],['1.375','light'],['1.55','moderate'],['1.725','high']]),select('goal',goalOptions)] : []));
|
||||
...(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));
|
||||
form.addEventListener('submit',async e=>{
|
||||
e.preventDefault();
|
||||
error.textContent='';
|
||||
let firstInvalid;
|
||||
for (const input of form.querySelectorAll('input,select')) {
|
||||
const measurement = measurements.includes(input.name);
|
||||
const valid = measurement ? validateMeasurement(input) : input.checkValidity();
|
||||
if (!valid) {
|
||||
firstInvalid ||= input;
|
||||
if (!measurement && !error.textContent) error.textContent=errorText(input.name);
|
||||
}
|
||||
}
|
||||
if (firstInvalid) {firstInvalid.focus();return;}
|
||||
if (!validateForm(form, error)) return;
|
||||
const body = Object.fromEntries(new FormData(form));
|
||||
form.setAttribute('aria-busy','true');for (const b of form.querySelectorAll('button')) b.disabled=true;
|
||||
try {
|
||||
|
||||
@ -2,6 +2,8 @@
|
||||
"ru": {
|
||||
"createGoalPlan": "Создать меню и план тренировок",
|
||||
"goalPlanHeading": "Меню и план тренировок",
|
||||
"publicPlanIntro": "Укажите данные о себе, чтобы рассчитать порции и подобрать число подходов по вашей цели. Расчёт выполняется на этой странице.",
|
||||
"publicPlanBack": "Назад",
|
||||
"goalPlanMissing": "Заполните возраст, рост, вес, пол, активность и цель. Создайте учётную запись, чтобы увидеть меню и план.",
|
||||
"goalPlanMenuHint": "Пример меню на каждый день. Порции рассчитаны для вашей цели.",
|
||||
"goalPlanDose": "{sets} × {reps} (подходы × повторения)",
|
||||
@ -78,8 +80,8 @@
|
||||
"sexHint": "Пол используется для оценки того, сколько калорий вам нужно в день. Результат — примерный ориентир.",
|
||||
"welcomeHeading": "Добро пожаловать",
|
||||
"welcomeIntro": "Ведите дневник питания и тренировок в одном месте.",
|
||||
"welcomeTitle": "Начните с учётной записи",
|
||||
"welcomeHint": "Нажмите «Далее», чтобы создать учётную запись. Если она уже есть, нажмите «Пропустить», чтобы войти.",
|
||||
"welcomeTitle": "Выберите цель",
|
||||
"welcomeHint": "«Далее» — создать учётную запись. «Пропустить» — войти.",
|
||||
"welcomeSkip": "Пропустить",
|
||||
"welcomeNext": "Далее",
|
||||
"planSignin": "Чтобы записать тренировку, войдите в свой профиль.",
|
||||
@ -92,6 +94,8 @@
|
||||
"kk": {
|
||||
"createGoalPlan": "Мәзір мен жаттығу жоспарын жасау",
|
||||
"goalPlanHeading": "Мәзір мен жаттығу жоспары",
|
||||
"publicPlanIntro": "Мақсатыңызға сай порциялар мен жаттығу тәсілдерінің санын есептеу үшін өзіңіз туралы деректерді енгізіңіз. Есеп осы бетте жасалады.",
|
||||
"publicPlanBack": "Артқа",
|
||||
"goalPlanMissing": "Жасыңызды, бойыңызды, салмағыңызды, жынысыңызды, белсенділігіңізді және мақсатыңызды көрсетіңіз. Мәзір мен жоспарды көру үшін есептік жазба жасаңыз.",
|
||||
"goalPlanMenuHint": "Күн сайынғы мәзір үлгісі. Үлес мөлшері мақсатыңызға сай есептелген.",
|
||||
"goalPlanDose": "{sets} × {reps} (тәсілдер × қайталаулар)",
|
||||
@ -168,8 +172,8 @@
|
||||
"sexHint": "Жынысыңыз күнделікті қанша калория қажет екенін бағалау үшін қолданылады. Нәтиже — шамамен бағдар.",
|
||||
"welcomeHeading": "Қош келдіңіз",
|
||||
"welcomeIntro": "Тамақтану мен жаттығу күнделігін бір жерде жүргізіңіз.",
|
||||
"welcomeTitle": "Тіркелгіден бастаңыз",
|
||||
"welcomeHint": "Тіркелгі жасау үшін «Келесі» түймесін басыңыз. Тіркелгіңіз бар болса, кіру үшін «Өткізіп жіберу» түймесін басыңыз.",
|
||||
"welcomeTitle": "Мақсатты таңдаңыз",
|
||||
"welcomeHint": "«Келесі» — тіркелгі жасау. «Өткізіп жіберу» — кіру.",
|
||||
"welcomeSkip": "Өткізіп жіберу",
|
||||
"welcomeNext": "Келесі",
|
||||
"planSignin": "Жаттығуды жазу үшін профиліңізге кіріңіз.",
|
||||
@ -182,6 +186,8 @@
|
||||
"en": {
|
||||
"createGoalPlan": "Create a meal and workout plan",
|
||||
"goalPlanHeading": "Meal and workout plan",
|
||||
"publicPlanIntro": "Enter your details to calculate meal portions and workout sets for your goal. The calculation runs on this page.",
|
||||
"publicPlanBack": "Back",
|
||||
"goalPlanMissing": "Enter your age, height, weight, sex, activity level and goal. Create an account to see your meal and workout plan.",
|
||||
"goalPlanMenuHint": "Sample menu for each day. Portions are calculated for your goal.",
|
||||
"goalPlanDose": "{sets} × {reps} (sets × reps)",
|
||||
@ -258,8 +264,8 @@
|
||||
"sexHint": "Your sex is used to estimate how many calories you need each day. The result is an approximate guide.",
|
||||
"welcomeHeading": "Welcome",
|
||||
"welcomeIntro": "Keep your food and workout diary in one place.",
|
||||
"welcomeTitle": "Start with your account",
|
||||
"welcomeHint": "Select Next to create an account. If you already have one, select Skip to sign in.",
|
||||
"welcomeTitle": "Choose your goal",
|
||||
"welcomeHint": "Choose Next to create an account or Skip to sign in.",
|
||||
"welcomeSkip": "Skip",
|
||||
"welcomeNext": "Next",
|
||||
"planSignin": "Sign in to your profile to log a workout.",
|
||||
|
||||
34
profile/nutrition.mjs
Normal file
34
profile/nutrition.mjs
Normal file
@ -0,0 +1,34 @@
|
||||
export class InputError extends Error {
|
||||
constructor(key, status = 400) { super(key); this.status = status; }
|
||||
}
|
||||
const goalFactors = {lose: 0.85, maintain: 1, gain: 1.1};
|
||||
export function validateProfile(input, defaultGoal = 'maintain') {
|
||||
const out = {};
|
||||
for (const [key, min, max] of [['height',100,250],['weight',25,350],['age',18,100]]) {
|
||||
const value = input[key];
|
||||
if (!['number','string'].includes(typeof value) || !/^\d+(?:[.,]\d+)?$/.test(String(value))) throw new InputError(key);
|
||||
out[key] = Number(String(value).replace(',', '.'));
|
||||
if (!Number.isFinite(out[key]) || out[key] < min || out[key] > max) throw new InputError(key);
|
||||
}
|
||||
if (!Number.isInteger(out.age)) throw new InputError('age');
|
||||
if (!['male','female'].includes(input.sex)) throw new InputError('sex');
|
||||
out.sex = input.sex;
|
||||
if (!['1.2','1.375','1.55','1.725'].includes(String(input.activity))) throw new InputError('activity');
|
||||
out.activity = Number(input.activity);
|
||||
const goal = input.goal === undefined ? defaultGoal : input.goal;
|
||||
if (typeof goal !== 'string' || !Object.hasOwn(goalFactors,goal)) throw new InputError('goal');
|
||||
out.goal = goal;
|
||||
return out;
|
||||
}
|
||||
export function nutrition(profile) {
|
||||
const p = validateProfile(profile);
|
||||
const calories = Math.round((10*p.weight + 6.25*p.height - 5*p.age + (p.sex === 'male' ? 5 : -161))*p.activity*goalFactors[p.goal]);
|
||||
const protein = Math.round(p.weight*1.6);
|
||||
// One illustrative day: proportions sum to the daily energy estimate.
|
||||
const menu = [
|
||||
{ name: 'breakfast', share: .3, kcal100: 130, protein100: 7 },
|
||||
{ name: 'lunch', share: .4, kcal100: 150, protein100: 12 },
|
||||
{ name: 'dinner', share: .3, kcal100: 140, protein100: 11 },
|
||||
].map(m => ({name:m.name, grams: Math.round(calories*m.share/m.kcal100*100), calories: Math.round(calories*m.share), protein: Math.round(calories*m.share/m.kcal100*m.protein100)}));
|
||||
return { calories, protein, menu };
|
||||
}
|
||||
@ -2,40 +2,8 @@ import { DatabaseSync } from 'node:sqlite';
|
||||
import { randomBytes, scrypt as derive, timingSafeEqual, createHash } from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
const scrypt = promisify(derive);
|
||||
export class InputError extends Error {
|
||||
constructor(key, status = 400) { super(key); this.status = status; }
|
||||
}
|
||||
const goalFactors = {lose: 0.85, maintain: 1, gain: 1.1};
|
||||
export function validateProfile(input, defaultGoal = 'maintain') {
|
||||
const out = {};
|
||||
for (const [key, min, max] of [['height',100,250],['weight',25,350],['age',18,100]]) {
|
||||
const value = input[key];
|
||||
if (!['number','string'].includes(typeof value) || !/^\d+(?:[.,]\d+)?$/.test(String(value))) throw new InputError(key);
|
||||
out[key] = Number(String(value).replace(',', '.'));
|
||||
if (!Number.isFinite(out[key]) || out[key] < min || out[key] > max) throw new InputError(key);
|
||||
}
|
||||
if (!Number.isInteger(out.age)) throw new InputError('age');
|
||||
if (!['male','female'].includes(input.sex)) throw new InputError('sex');
|
||||
out.sex = input.sex;
|
||||
if (!['1.2','1.375','1.55','1.725'].includes(String(input.activity))) throw new InputError('activity');
|
||||
out.activity = Number(input.activity);
|
||||
const goal = input.goal === undefined ? defaultGoal : input.goal;
|
||||
if (typeof goal !== 'string' || !Object.hasOwn(goalFactors,goal)) throw new InputError('goal');
|
||||
out.goal = goal;
|
||||
return out;
|
||||
}
|
||||
export function nutrition(profile) {
|
||||
const p = validateProfile(profile);
|
||||
const calories = Math.round((10*p.weight + 6.25*p.height - 5*p.age + (p.sex === 'male' ? 5 : -161))*p.activity*goalFactors[p.goal]);
|
||||
const protein = Math.round(p.weight*1.6);
|
||||
// One illustrative day: proportions sum to the daily energy estimate.
|
||||
const menu = [
|
||||
{ name: 'breakfast', share: .3, kcal100: 130, protein100: 7 },
|
||||
{ name: 'lunch', share: .4, kcal100: 150, protein100: 12 },
|
||||
{ name: 'dinner', share: .3, kcal100: 140, protein100: 11 },
|
||||
].map(m => ({name:m.name, grams: Math.round(calories*m.share/m.kcal100*100), calories: Math.round(calories*m.share), protein: Math.round(calories*m.share/m.kcal100*m.protein100)}));
|
||||
return { calories, protein, menu };
|
||||
}
|
||||
import { InputError, validateProfile, nutrition } from './nutrition.mjs';
|
||||
export { InputError, validateProfile, nutrition };
|
||||
const hash = value => createHash('sha256').update(value).digest('hex');
|
||||
export class ProfileService {
|
||||
constructor(file, {now = () => Date.now()} = {}) {
|
||||
|
||||
@ -12,3 +12,11 @@
|
||||
@media(max-width:600px){.auth-login h1{font-size:1.65rem;margin:16px 0 8px}.auth-login>p{margin:8px 0}.auth-login form.card{margin:12px 0;padding:14px}.auth-login [data-auth-guidance]{margin:0 0 12px}.auth-login .grid{gap:10px}.auth-login .actions{margin-top:12px;gap:8px}.auth-login .error:empty{display:none}.auth-login .actions button{width:100%}}
|
||||
|
||||
@media(max-width:600px){.auth-form{padding-bottom:170px}.auth-form form .actions{position:fixed;bottom:0;left:0;right:0;z-index:10;display:grid;gap:8px;margin:0;padding:10px 16px max(10px,env(safe-area-inset-bottom));background:#fff;border-top:1px solid #d5dfd5}.auth-form form .actions button{width:100%}.auth-form input,.auth-form select{scroll-margin-bottom:170px}}
|
||||
|
||||
.welcome [data-public-calculation]{width:100%;margin-top:8px}
|
||||
@media(max-width:600px){
|
||||
.welcome-screen h1{margin:16px 0 8px}
|
||||
.welcome-screen>p{margin:8px 0}
|
||||
.welcome-screen .welcome{margin:12px 0;padding:14px}
|
||||
.welcome-screen .welcome .actions{margin-top:10px}
|
||||
}
|
||||
|
||||
56
tests/browser/public-menu-plan.spec.js
Normal file
56
tests/browser/public-menu-plan.spec.js
Normal file
@ -0,0 +1,56 @@
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const translations = require('../../profile/i18n.json');
|
||||
|
||||
test.use({ viewport: { width: 360, height: 640 }, isMobile: true, hasTouch: true });
|
||||
|
||||
for (const lang of ['ru', 'kk', 'en']) {
|
||||
test(`Расчёт меню и плана с приветствия (${lang})`, async ({ page }) => {
|
||||
const text = translations[lang];
|
||||
const writes = [];
|
||||
page.on('request', request => {
|
||||
if (request.method() !== 'GET') writes.push(request.url());
|
||||
});
|
||||
await page.goto('/?lang=' + lang);
|
||||
const open = page.getByRole('button', { name: text.createGoalPlan, exact: true });
|
||||
await expect(open).toBeInViewport({ ratio: 1 });
|
||||
await page.locator('#welcome-goal').selectOption('lose');
|
||||
await open.click();
|
||||
await expect(page.getByRole('heading', { level: 1 })).toHaveText(text.goalPlanHeading);
|
||||
await expect(page.locator('#field-goal')).toHaveValue('lose');
|
||||
await expect(page.locator('#field-password, #field-username')).toHaveCount(0);
|
||||
await page.locator('#field-height').fill('175');
|
||||
await page.locator('#field-weight').fill('75');
|
||||
await page.locator('#field-age').fill('30');
|
||||
await page.locator('#field-sex').selectOption('male');
|
||||
await page.locator('#field-activity').selectOption('1.375');
|
||||
await open.click();
|
||||
|
||||
const days = page.locator('[data-goal-plan-day]');
|
||||
await expect(days).toHaveCount(4);
|
||||
await expect(days.first()).toContainText(`${text.breakfast} · 458 ${text.grams}`);
|
||||
await expect(days.first()).toContainText(text.goalPlanDose.replace('{sets}', '2').replace('{reps}', '10'));
|
||||
await page.locator('#field-goal').selectOption('gain');
|
||||
await expect(days).toHaveCount(0);
|
||||
await open.click();
|
||||
await expect(days.first()).toContainText(text.goalPlanDose.replace('{sets}', '4').replace('{reps}', '10'));
|
||||
await expect(days.first()).not.toContainText(`${text.breakfast} · 458 ${text.grams}`);
|
||||
expect(writes).toEqual([]);
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(360);
|
||||
|
||||
await page.getByRole('button', { name: text.publicPlanBack, exact: true }).click();
|
||||
await page.locator('[data-welcome-skip]').click();
|
||||
await expect(open).toBeVisible();
|
||||
});
|
||||
}
|
||||
|
||||
test('Рост вне диапазона не даёт рассчитать меню и план', async ({ page }) => {
|
||||
await page.goto('/?lang=ru');
|
||||
const create = page.getByRole('button', { name: translations.ru.createGoalPlan, exact: true });
|
||||
await create.click();
|
||||
const height = page.locator('#field-height');
|
||||
await height.fill('5');
|
||||
await create.click();
|
||||
await expect(height).toBeFocused();
|
||||
await expect(page.locator('#field-height-error')).toHaveText(translations.ru.errors.height);
|
||||
await expect(page.locator('[data-goal-plan-day]')).toHaveCount(0);
|
||||
});
|
||||
@ -45,7 +45,7 @@ test('Пропуск открывает вход без данных',async({pag
|
||||
await expect(page.locator('.welcome')).toHaveCount(0);
|
||||
});
|
||||
test('Вошедший пользователь видит профиль без приветствия',async({page})=>{
|
||||
await page.route('**/api/profile',route=>route.fulfill({json:{profile:{username:'mock-user',height:182,weight:81,age:32,sex:'female',activity:1.375},nutrition:{calories:2000,protein:100,menu:[]}}}));
|
||||
await page.route('**/api/profile',route=>route.fulfill({json:{profile:{username:'mock-user',height:182,weight:81,age:32,sex:'female',activity:1.375,goal:'maintain'},nutrition:{calories:2000,protein:100,menu:[]}}}));
|
||||
await page.goto('/?lang=ru');
|
||||
await expect(page.locator('#field-height')).toHaveValue('182');
|
||||
await expect(page.locator('.welcome')).toHaveCount(0);
|
||||
|
||||
Loading…
Reference in New Issue
Block a user