From 1df242e681c79fb189bd1901b8a7361cdcc76d72 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Wed, 25 Nov 2026 12:43:53 +0000 Subject: [PATCH 1/2] =?UTF-8?q?TPTIP-89:=20=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2?= =?UTF-8?q?=D0=B8=D1=82=D1=8C=20=D1=80=D0=B0=D1=81=D1=87=D1=91=D1=82=20?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D1=8E=20=D0=B8=20=D1=82=D1=80=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=80=D0=BE=D0=B2=D0=BE=D0=BA=20=D0=B4=D0=BE=20=D0=B2?= =?UTF-8?q?=D1=85=D0=BE=D0=B4=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/glossary.md | 2 + .../tptip-89-public-menu-plan/.openspec.yaml | 2 + .../tptip-89-public-menu-plan/design.md | 15 ++ .../tptip-89-public-menu-plan/proposal.md | 27 +++ .../specs/public-menu-plan/spec.md | 22 +++ .../tptip-89-public-menu-plan/tasks.md | 8 + profile-server.mjs | 2 +- profile/app.js | 154 ++++++++++++++---- profile/i18n.json | 6 + profile/nutrition.mjs | 34 ++++ profile/service.mjs | 36 +--- profile/style.css | 2 + 12 files changed, 240 insertions(+), 70 deletions(-) create mode 100644 openspec/changes/tptip-89-public-menu-plan/.openspec.yaml create mode 100644 openspec/changes/tptip-89-public-menu-plan/design.md create mode 100644 openspec/changes/tptip-89-public-menu-plan/proposal.md create mode 100644 openspec/changes/tptip-89-public-menu-plan/specs/public-menu-plan/spec.md create mode 100644 openspec/changes/tptip-89-public-menu-plan/tasks.md create mode 100644 profile/nutrition.mjs diff --git a/docs/glossary.md b/docs/glossary.md index 7db39ba..b9b2ab5 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -69,3 +69,5 @@ | Меню и упражнения по цели | Создать меню и план тренировок, Меню и план тренировок, Пример меню на каждый день, подходы, повторения | генерация, сет | Результат в профиле. До расчёта указываем, какие данные нужно заполнить | | Экран дневника за день | Сегодня, + Еда, + Тренировка, + Вода | — | Вкладка открывает выбранный день. Кнопка воды добавляет 250 мл | + +| Расчёт до входа | Создать меню и план тренировок, Назад | — | Возраст, рост, вес, пол для расчёта, активность и цель используются на открытой странице | diff --git a/openspec/changes/tptip-89-public-menu-plan/.openspec.yaml b/openspec/changes/tptip-89-public-menu-plan/.openspec.yaml new file mode 100644 index 0000000..462e04d --- /dev/null +++ b/openspec/changes/tptip-89-public-menu-plan/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-25 diff --git a/openspec/changes/tptip-89-public-menu-plan/design.md b/openspec/changes/tptip-89-public-menu-plan/design.md new file mode 100644 index 0000000..827047b --- /dev/null +++ b/openspec/changes/tptip-89-public-menu-plan/design.md @@ -0,0 +1,15 @@ +# Design + +## Context + +Расчёт для профиля и проверка измерений находятся в серверном модуле. Карточка профиля уже показывает меню и упражнения по цели. + +## Decisions + +- Открывать форму из приветствия и экрана входа. Переносить выбранную на приветствии цель и давать изменить её в форме. +- Вынести чистый расчёт с проверкой данных в общий модуль для браузера и сервера. Значения формы и результат держать в памяти страницы, расчёт выполняется на устройстве пользователя. +- Использовать существующие поля, упражнения, порции и переводы. После редактирования нужно нажать кнопку расчёта снова. + +## Risks / Trade-offs + +Общий модуль должен отдаваться основным сервером. Проверка браузером проходит через входную страницу настоящего сервера. diff --git a/openspec/changes/tptip-89-public-menu-plan/proposal.md b/openspec/changes/tptip-89-public-menu-plan/proposal.md new file mode 100644 index 0000000..516207f --- /dev/null +++ b/openspec/changes/tptip-89-public-menu-plan/proposal.md @@ -0,0 +1,27 @@ +# Proposal + +[TPTIP-89](https://peppa.telecom.quest) — дать пользователю рассчитать меню и план тренировок до входа. + +## Why + +На первом экране можно выбрать цель, но расчёт доступен только после создания учётной записи. + +## What Changes + +- Добавить кнопку «Создать меню и план тренировок» на приветствии и экране входа. +- Открывать отдельную форму с возрастом, ростом, весом, полом для расчёта, активностью и целью. +- После заполнения показывать пример меню с порциями и четыре дня тренировок. + +## Capabilities + +### New Capabilities + +- `public-menu-plan` — расчёт меню и плана тренировок без входа. + +## Impact + +Публичный экран, переводы, общий расчёт питания и браузерная проверка. Создание учётной записи и сохранение плана вне задачи. + +## Открытые вопросы + +Нет. diff --git a/openspec/changes/tptip-89-public-menu-plan/specs/public-menu-plan/spec.md b/openspec/changes/tptip-89-public-menu-plan/specs/public-menu-plan/spec.md new file mode 100644 index 0000000..a35c400 --- /dev/null +++ b/openspec/changes/tptip-89-public-menu-plan/specs/public-menu-plan/spec.md @@ -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** результат не показан diff --git a/openspec/changes/tptip-89-public-menu-plan/tasks.md b/openspec/changes/tptip-89-public-menu-plan/tasks.md new file mode 100644 index 0000000..5ac7507 --- /dev/null +++ b/openspec/changes/tptip-89-public-menu-plan/tasks.md @@ -0,0 +1,8 @@ +## 1. Форма и расчёт + +- [x] 1.1 Открыть публичную форму из приветствия и экрана входа, добавить тексты на русском, казахском и английском. +- [x] 1.2 Подключить общий расчёт и показать порции и четыре дня тренировок. + +## 2. Проверка + +- [ ] 2.1 Проверить в браузере расчёт и ошибку ввода до входа, запустить проверки проекта и `openspec validate`. diff --git a/profile-server.mjs b/profile-server.mjs index 8344e7f..5f3364f 100644 --- a/profile-server.mjs +++ b/profile-server.mjs @@ -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')); diff --git a/profile/app.js b/profile/app.js index 4ee8268..1972ebc 100644 --- a/profile/app.js +++ b/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,12 @@ 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('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 +272,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 { diff --git a/profile/i18n.json b/profile/i18n.json index 2c9abb5..96761eb 100644 --- a/profile/i18n.json +++ b/profile/i18n.json @@ -2,6 +2,8 @@ "ru": { "createGoalPlan": "Создать меню и план тренировок", "goalPlanHeading": "Меню и план тренировок", + "publicPlanIntro": "Укажите данные о себе, чтобы рассчитать порции и подобрать число подходов по вашей цели. Расчёт выполняется на этой странице.", + "publicPlanBack": "Назад", "goalPlanMissing": "Заполните возраст, рост, вес, пол, активность и цель. Создайте учётную запись, чтобы увидеть меню и план.", "goalPlanMenuHint": "Пример меню на каждый день. Порции рассчитаны для вашей цели.", "goalPlanDose": "{sets} × {reps} (подходы × повторения)", @@ -92,6 +94,8 @@ "kk": { "createGoalPlan": "Мәзір мен жаттығу жоспарын жасау", "goalPlanHeading": "Мәзір мен жаттығу жоспары", + "publicPlanIntro": "Мақсатыңызға сай порциялар мен жаттығу тәсілдерінің санын есептеу үшін өзіңіз туралы деректерді енгізіңіз. Есеп осы бетте жасалады.", + "publicPlanBack": "Артқа", "goalPlanMissing": "Жасыңызды, бойыңызды, салмағыңызды, жынысыңызды, белсенділігіңізді және мақсатыңызды көрсетіңіз. Мәзір мен жоспарды көру үшін есептік жазба жасаңыз.", "goalPlanMenuHint": "Күн сайынғы мәзір үлгісі. Үлес мөлшері мақсатыңызға сай есептелген.", "goalPlanDose": "{sets} × {reps} (тәсілдер × қайталаулар)", @@ -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)", diff --git a/profile/nutrition.mjs b/profile/nutrition.mjs new file mode 100644 index 0000000..d6ebcec --- /dev/null +++ b/profile/nutrition.mjs @@ -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 }; +} diff --git a/profile/service.mjs b/profile/service.mjs index 81e1682..4e7a730 100644 --- a/profile/service.mjs +++ b/profile/service.mjs @@ -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()} = {}) { diff --git a/profile/style.css b/profile/style.css index f73c88f..6f5d323 100644 --- a/profile/style.css +++ b/profile/style.css @@ -12,3 +12,5 @@ @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} From 15c2e95f9f5873acf6e93967b94eab748f51c684 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Wed, 25 Nov 2026 12:47:37 +0000 Subject: [PATCH 2/2] =?UTF-8?q?TPTIP-89:=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=B8=D1=82=D1=8C=20=D1=80=D0=B0=D1=81=D1=87=D1=91=D1=82?= =?UTF-8?q?=20=D0=BD=D0=B0=20=D1=82=D0=B5=D0=BB=D0=B5=D1=84=D0=BE=D0=BD?= =?UTF-8?q?=D0=B5=20=D0=B8=20=D0=B0=D1=80=D1=85=D0=B8=D0=B2=D0=B8=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D1=82=D1=8C=20=D1=81=D0=BF=D0=B5=D1=86=D0=B8?= =?UTF-8?q?=D1=84=D0=B8=D0=BA=D0=B0=D1=86=D0=B8=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .peppa/memory.md | 4 +- docs/glossary.md | 2 +- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/public-menu-plan/spec.md | 0 .../tasks.md | 2 +- openspec/specs/public-menu-plan/spec.md | 23 ++++++++ profile/app.js | 1 + profile/i18n.json | 12 ++-- profile/style.css | 6 ++ tests/browser/public-menu-plan.spec.js | 56 +++++++++++++++++++ tests/browser/public-welcome.spec.js | 2 +- 13 files changed, 96 insertions(+), 12 deletions(-) rename openspec/changes/{tptip-89-public-menu-plan => archive/2026-11-25-tptip-89-public-menu-plan}/.openspec.yaml (100%) rename openspec/changes/{tptip-89-public-menu-plan => archive/2026-11-25-tptip-89-public-menu-plan}/design.md (100%) rename openspec/changes/{tptip-89-public-menu-plan => archive/2026-11-25-tptip-89-public-menu-plan}/proposal.md (100%) rename openspec/changes/{tptip-89-public-menu-plan => archive/2026-11-25-tptip-89-public-menu-plan}/specs/public-menu-plan/spec.md (100%) rename openspec/changes/{tptip-89-public-menu-plan => archive/2026-11-25-tptip-89-public-menu-plan}/tasks.md (88%) create mode 100644 openspec/specs/public-menu-plan/spec.md create mode 100644 tests/browser/public-menu-plan.spec.js diff --git a/.peppa/memory.md b/.peppa/memory.md index cb761fd..03c0357 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -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): «Укажите/Проверьте : … Введите число .»; нормы второго шага (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: блюдо дня зависит от даты; для теста с фото выбирайте овсянку через «+ Рецепт». diff --git a/docs/glossary.md b/docs/glossary.md index b9b2ab5..3c655bd 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -70,4 +70,4 @@ | Экран дневника за день | Сегодня, + Еда, + Тренировка, + Вода | — | Вкладка открывает выбранный день. Кнопка воды добавляет 250 мл | -| Расчёт до входа | Создать меню и план тренировок, Назад | — | Возраст, рост, вес, пол для расчёта, активность и цель используются на открытой странице | +| Расчёт до входа | Выберите цель, Создать меню и план тренировок, Назад | — | Возраст, рост, вес, пол для расчёта, активность и цель используются на открытой странице | diff --git a/openspec/changes/tptip-89-public-menu-plan/.openspec.yaml b/openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/.openspec.yaml similarity index 100% rename from openspec/changes/tptip-89-public-menu-plan/.openspec.yaml rename to openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/.openspec.yaml diff --git a/openspec/changes/tptip-89-public-menu-plan/design.md b/openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/design.md similarity index 100% rename from openspec/changes/tptip-89-public-menu-plan/design.md rename to openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/design.md diff --git a/openspec/changes/tptip-89-public-menu-plan/proposal.md b/openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/proposal.md similarity index 100% rename from openspec/changes/tptip-89-public-menu-plan/proposal.md rename to openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/proposal.md diff --git a/openspec/changes/tptip-89-public-menu-plan/specs/public-menu-plan/spec.md b/openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/specs/public-menu-plan/spec.md similarity index 100% rename from openspec/changes/tptip-89-public-menu-plan/specs/public-menu-plan/spec.md rename to openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/specs/public-menu-plan/spec.md diff --git a/openspec/changes/tptip-89-public-menu-plan/tasks.md b/openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/tasks.md similarity index 88% rename from openspec/changes/tptip-89-public-menu-plan/tasks.md rename to openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/tasks.md index 5ac7507..f43f911 100644 --- a/openspec/changes/tptip-89-public-menu-plan/tasks.md +++ b/openspec/changes/archive/2026-11-25-tptip-89-public-menu-plan/tasks.md @@ -5,4 +5,4 @@ ## 2. Проверка -- [ ] 2.1 Проверить в браузере расчёт и ошибку ввода до входа, запустить проверки проекта и `openspec validate`. +- [x] 2.1 Проверить в браузере расчёт и ошибку ввода до входа, запустить проверки проекта и `openspec validate`. diff --git a/openspec/specs/public-menu-plan/spec.md b/openspec/specs/public-menu-plan/spec.md new file mode 100644 index 0000000..9fe509a --- /dev/null +++ b/openspec/specs/public-menu-plan/spec.md @@ -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** результат не показан diff --git a/profile/app.js b/profile/app.js index 1972ebc..3214098 100644 --- a/profile/app.js +++ b/profile/app.js @@ -251,6 +251,7 @@ function goalPlanCard() { } function render() { document.documentElement.lang=lang;document.title=t('app'); + 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()))); diff --git a/profile/i18n.json b/profile/i18n.json index 96761eb..3bab165 100644 --- a/profile/i18n.json +++ b/profile/i18n.json @@ -80,8 +80,8 @@ "sexHint": "Пол используется для оценки того, сколько калорий вам нужно в день. Результат — примерный ориентир.", "welcomeHeading": "Добро пожаловать", "welcomeIntro": "Ведите дневник питания и тренировок в одном месте.", - "welcomeTitle": "Начните с учётной записи", - "welcomeHint": "Нажмите «Далее», чтобы создать учётную запись. Если она уже есть, нажмите «Пропустить», чтобы войти.", + "welcomeTitle": "Выберите цель", + "welcomeHint": "«Далее» — создать учётную запись. «Пропустить» — войти.", "welcomeSkip": "Пропустить", "welcomeNext": "Далее", "planSignin": "Чтобы записать тренировку, войдите в свой профиль.", @@ -172,8 +172,8 @@ "sexHint": "Жынысыңыз күнделікті қанша калория қажет екенін бағалау үшін қолданылады. Нәтиже — шамамен бағдар.", "welcomeHeading": "Қош келдіңіз", "welcomeIntro": "Тамақтану мен жаттығу күнделігін бір жерде жүргізіңіз.", - "welcomeTitle": "Тіркелгіден бастаңыз", - "welcomeHint": "Тіркелгі жасау үшін «Келесі» түймесін басыңыз. Тіркелгіңіз бар болса, кіру үшін «Өткізіп жіберу» түймесін басыңыз.", + "welcomeTitle": "Мақсатты таңдаңыз", + "welcomeHint": "«Келесі» — тіркелгі жасау. «Өткізіп жіберу» — кіру.", "welcomeSkip": "Өткізіп жіберу", "welcomeNext": "Келесі", "planSignin": "Жаттығуды жазу үшін профиліңізге кіріңіз.", @@ -264,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.", diff --git a/profile/style.css b/profile/style.css index 6f5d323..a51448c 100644 --- a/profile/style.css +++ b/profile/style.css @@ -14,3 +14,9 @@ @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} +} diff --git a/tests/browser/public-menu-plan.spec.js b/tests/browser/public-menu-plan.spec.js new file mode 100644 index 0000000..373d2c1 --- /dev/null +++ b/tests/browser/public-menu-plan.spec.js @@ -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); +}); diff --git a/tests/browser/public-welcome.spec.js b/tests/browser/public-welcome.spec.js index 8fd9f35..1ead315 100644 --- a/tests/browser/public-welcome.spec.js +++ b/tests/browser/public-welcome.spec.js @@ -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);