From c30a8d6501f889bf90ed2fa3dc31cced86d00b4d Mon Sep 17 00:00:00 2001 From: Peppa Date: Fri, 20 Nov 2026 15:36:43 +0500 Subject: [PATCH 1/5] =?UTF-8?q?TPTIP-83:=20=D0=BE=D0=BF=D0=B8=D1=81=D0=B0?= =?UTF-8?q?=D1=82=D1=8C=20=D0=B4=D0=BE=D1=81=D1=82=D1=83=D0=BF=20=D0=BA=20?= =?UTF-8?q?=D0=BC=D0=B5=D0=BD=D1=8E=20=D0=B8=20=D0=BF=D0=BB=D0=B0=D0=BD?= =?UTF-8?q?=D1=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../.openspec.yaml | 2 ++ .../design.md | 19 ++++++++++++ .../proposal.md | 25 ++++++++++++++++ .../specs/private-profile/spec.md | 30 +++++++++++++++++++ .../tasks.md | 8 +++++ 5 files changed, 84 insertions(+) create mode 100644 openspec/changes/tptip-83-show-food-and-workout-menu/.openspec.yaml create mode 100644 openspec/changes/tptip-83-show-food-and-workout-menu/design.md create mode 100644 openspec/changes/tptip-83-show-food-and-workout-menu/proposal.md create mode 100644 openspec/changes/tptip-83-show-food-and-workout-menu/specs/private-profile/spec.md create mode 100644 openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/.openspec.yaml b/openspec/changes/tptip-83-show-food-and-workout-menu/.openspec.yaml new file mode 100644 index 0000000..4ee7b3f --- /dev/null +++ b/openspec/changes/tptip-83-show-food-and-workout-menu/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-20 diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/design.md b/openspec/changes/tptip-83-show-food-and-workout-menu/design.md new file mode 100644 index 0000000..761947f --- /dev/null +++ b/openspec/changes/tptip-83-show-food-and-workout-menu/design.md @@ -0,0 +1,19 @@ +# Design + +## Context + +Профиль хранится в SQLite как JSON. Публичное приветствие держит цель до регистрации. Дневник получает сохранённый профиль с сервера. + +## Goals / Non-Goals + +Показать меню и план после регистрации, из профиля и дневника. Сохранить существующий набор блюд и готовый план. + +## Decisions + +- Сохраняем цель в JSON профиля. Для записей без цели используем поддержание. Запрос редактирования без цели сохраняет прежний выбор. +- Применяем множители из дневника (0,85 / 1 / 1,10) до расчёта порций. Расчёт белка остаётся прежним. Дневник использует цель профиля для остальных норм. +- Переход к меню ведёт к заголовку результата в профиле. План открывается по существующему адресу дневника с выбранным языком. До регистрации форма поясняет, когда появится результат. + +## Risks / Trade-offs + +Узкий экран требует проверить доступность обоих переходов без прокрутки. Старые профили и клиенты проверяем отдельно. diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/proposal.md b/openspec/changes/tptip-83-show-food-and-workout-menu/proposal.md new file mode 100644 index 0000000..4fa9a14 --- /dev/null +++ b/openspec/changes/tptip-83-show-food-and-workout-menu/proposal.md @@ -0,0 +1,25 @@ +[TPTIP-83](https://peppa.telecom.quest) — сделать меню питания на день и план тренировок доступными после заполнения профиля. + +## Why + +Пример меню находится ниже формы профиля, а цель с приветствия не влияет на порции. Пользователю нужен прямой переход к обоим результатам. + +## What Changes + +- Показать переходы к меню питания и плану тренировок вверху профиля и на главной дневника. +- Сохранить выбранную цель и учесть её при расчёте калорий и порций. +- До расчёта объяснить, куда ввести данные. + +## Capabilities + +### Modified Capabilities + +- `private-profile` — доступ к результатам и расчёт меню по цели. + +## Impact + +Формы профиля, дневник, локализация и расчёт на сервере. Вне задачи создание новых рецептов и индивидуальных тренировок. + +## Вопросы к PM + +Нет. diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/specs/private-profile/spec.md b/openspec/changes/tptip-83-show-food-and-workout-menu/specs/private-profile/spec.md new file mode 100644 index 0000000..8ab67fd --- /dev/null +++ b/openspec/changes/tptip-83-show-food-and-workout-menu/specs/private-profile/spec.md @@ -0,0 +1,30 @@ +## ADDED Requirements + +### Requirement: Доступ к меню питания и плану тренировок +Система SHALL показывать в профиле и на главной дневника переходы к примеру меню на день и плану тренировок. Пока данные не введены, регистрация SHALL объяснять, как получить результаты. + +#### Scenario: Результаты доступны после регистрации +- **GIVEN** пользователь заполнил имя, пароль, возраст 30, рост 175, вес 75, мужской пол и лёгкую активность +- **WHEN** он создаёт учётную запись +- **THEN** видны переходы «Открыть меню на день» и «План тренировок» +- **AND** в меню указаны завтрак, обед и ужин с порциями + +#### Scenario: Данные ещё не заполнены +- **GIVEN** посетитель без учётной записи видит приветствие +- **WHEN** он нажимает «Далее» +- **THEN** форма предлагает заполнить данные, чтобы увидеть меню и план +- **AND** меню с рассчитанными порциями отсутствует + +### Requirement: Меню с учётом цели +Система SHALL сохранять выбранную цель в профиле и рассчитывать калории и размеры порций по ней. Для профиля без сохранённой цели система SHALL использовать поддержание. + +#### Scenario: Цель «Похудение» применяется к меню +- **GIVEN** пользователь 30 лет, ростом 175 см и весом 75 кг выбрал мужской пол, лёгкую активность и «Похудение» +- **WHEN** он создаёт учётную запись +- **THEN** дневной ориентир составляет 1985 ккал +- **AND** у завтрака указано 596 ккал + +#### Scenario: Ранее созданный профиль без цели +- **GIVEN** у пользователя сохранены возраст 30, рост 175, вес 75, мужской пол и лёгкая активность без цели +- **WHEN** он входит в профиль +- **THEN** выбрано «Поддержание» и дневной ориентир составляет 2336 ккал diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md b/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md new file mode 100644 index 0000000..96c011f --- /dev/null +++ b/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md @@ -0,0 +1,8 @@ +## 1. Реализация + +- [ ] 1.1 Сохранить цель в профиле и применить её к расчёту и дневным нормам. +- [ ] 1.2 Добавить переход к меню из профиля и дневника, сохранить переход к плану и перевести подсказку регистрации. + +## 2. Проверка + +- [ ] 2.1 Проверить результаты и сохранение цели в браузере, запустить проверки проекта и openspec validate. -- 2.45.2 From 0bcba0be2e7ee513603db409dafdd9393e47d8c8 Mon Sep 17 00:00:00 2001 From: Peppa Date: Fri, 20 Nov 2026 15:37:02 +0500 Subject: [PATCH 2/5] =?UTF-8?q?TPTIP-83:=20=D1=83=D1=87=D0=B8=D1=82=D1=8B?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D1=8C=20=D1=86=D0=B5=D0=BB=D1=8C=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D1=84=D0=B8=D0=BB=D1=8F=20=D0=B2=20=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.html | 1 + .../tptip-83-show-food-and-workout-menu/tasks.md | 2 +- profile/service.mjs | 12 ++++++++---- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/index.html b/index.html index 31a7c4b..c6c1611 100644 --- a/index.html +++ b/index.html @@ -445,6 +445,7 @@ function applyPrivateProfile() { const personal = window.TPTProfile; delete db.settings.normsPending; db.settings.profile = { ...personal.profile, sex: personal.profile.sex === 'male' ? 'm' : 'f' }; + db.settings.goal = personal.profile.goal; Object.assign(db.settings, suggestNorms(db.settings.goal, db.settings.profile), { onboarded: true }); db.settings.kcal = personal.nutrition.calories; db.settings.protein = personal.nutrition.protein; diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md b/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md index 96c011f..7d82e76 100644 --- a/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md +++ b/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md @@ -1,6 +1,6 @@ ## 1. Реализация -- [ ] 1.1 Сохранить цель в профиле и применить её к расчёту и дневным нормам. +- [x] 1.1 Сохранить цель в профиле и применить её к расчёту и дневным нормам. - [ ] 1.2 Добавить переход к меню из профиля и дневника, сохранить переход к плану и перевести подсказку регистрации. ## 2. Проверка diff --git a/profile/service.mjs b/profile/service.mjs index d86b46c..81e1682 100644 --- a/profile/service.mjs +++ b/profile/service.mjs @@ -5,7 +5,8 @@ const scrypt = promisify(derive); export class InputError extends Error { constructor(key, status = 400) { super(key); this.status = status; } } -export function validateProfile(input) { +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]; @@ -18,11 +19,14 @@ export function validateProfile(input) { 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); + 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 = [ @@ -72,11 +76,11 @@ export class ProfileService { return user; } read(token) { - const user = this.user(token), profile = JSON.parse(user.profile); + const user = this.user(token), profile = validateProfile(JSON.parse(user.profile)); return {username:user.username,profile,nutrition:nutrition(profile)}; } update(token,input) { - const user = this.user(token), profile = validateProfile(input); + const user = this.user(token), profile = validateProfile(input,JSON.parse(user.profile).goal); this.db.prepare('UPDATE users SET profile=? WHERE id=?').run(JSON.stringify(profile),user.id); return this.read(token); } -- 2.45.2 From cbc7a62a912b4e19a82025a159d0cbcfa9f79ea6 Mon Sep 17 00:00:00 2001 From: Peppa Date: Fri, 20 Nov 2026 15:37:34 +0500 Subject: [PATCH 3/5] =?UTF-8?q?TPTIP-83:=20=D0=BE=D1=82=D0=BA=D1=80=D1=8B?= =?UTF-8?q?=D1=82=D1=8C=20=D0=BC=D0=B5=D0=BD=D1=8E=20=D0=B8=D0=B7=20=D0=BF?= =?UTF-8?q?=D1=80=D0=BE=D1=84=D0=B8=D0=BB=D1=8F=20=D0=B8=20=D0=B4=D0=BD?= =?UTF-8?q?=D0=B5=D0=B2=D0=BD=D0=B8=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/glossary.md | 2 ++ index.html | 1 + .../tptip-83-show-food-and-workout-menu/tasks.md | 2 +- profile-server.mjs | 4 ++-- profile/app.js | 11 +++++++---- profile/i18n.json | 12 +++++++++--- 6 files changed, 22 insertions(+), 10 deletions(-) diff --git a/docs/glossary.md b/docs/glossary.md index 022fb36..d929ad1 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -63,3 +63,5 @@ | Длина пароля | От 12 до 128 символов. Длинный пароль помогает защитить ваш профиль. | сложность пароля | Подсказка под полем пароля | | Ошибка входа | Имя или пароль не подошли. Проверьте их или создайте учётную запись. | имя не существует, неверный пароль | Одинаковое сообщение при неверном имени и пароле | + +| Переход к рассчитанному меню | Открыть меню на день | — | Показывает пример меню с порциями для выбранной цели | diff --git a/index.html b/index.html index c6c1611..bc35eff 100644 --- a/index.html +++ b/index.html @@ -722,6 +722,7 @@ function viewToday() { return h('div', null, dateNav(), h('div', { class: 'card' }, h('button', { class: 'primary', style: 'width:100%', 'data-plan-open': '', 'aria-describedby': 'planWhat', onclick: openPlan }, planHome.button), h('p', { id: 'planWhat', class: 'small muted', 'data-plan-what': '', style: 'margin:8px 0 0' }, planHome.what), + window.TPTProfile ? h('a', { href: '/?lang=' + gymLang + '#daily-menu', 'data-menu-open': '' }, window.TPTMenuText) : null, db.workouts.length ? null : h('p', { class: 'small muted', 'data-plan-start': '', style: 'margin:4px 0 0' }, h('button', { class: 'link-btn', style: 'text-align:left', onclick: openPlan }, planHome.start))), s.normsPending ? h('div', { class: 'card', 'data-norms-pending': '' }, h('b', null, 'Дневные нормы пока не рассчитаны'), h('p', { class: 'small muted', style: 'margin:6px 0 8px' }, 'Сейчас показаны примерные цифры. Укажите возраст, рост и вес в «Настройках» — и нормы станут вашими.'), diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md b/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md index 7d82e76..a4118c0 100644 --- a/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md +++ b/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md @@ -1,7 +1,7 @@ ## 1. Реализация - [x] 1.1 Сохранить цель в профиле и применить её к расчёту и дневным нормам. -- [ ] 1.2 Добавить переход к меню из профиля и дневника, сохранить переход к плану и перевести подсказку регистрации. +- [x] 1.2 Добавить переход к меню из профиля и дневника, сохранить переход к плану и перевести подсказку регистрации. ## 2. Проверка diff --git a/profile-server.mjs b/profile-server.mjs index eec2495..8344e7f 100644 --- a/profile-server.mjs +++ b/profile-server.mjs @@ -37,9 +37,9 @@ export function createApp({database,secure = process.env.NODE_ENV === 'productio try { personal=service.read(token); } catch { res.writeHead(302,{Location:'/'});res.end();return; } const lang = new URL(req.url,'http://localhost').searchParams.get('lang'); const dictionaries = JSON.parse(await readFile(resolve(root,'profile/i18n.json'),'utf8')); - const text = (dictionaries[lang] || dictionaries.ru).profile; + const text = Object.hasOwn(dictionaries,lang) ? dictionaries[lang] : dictionaries.ru; let html = await readFile(resolve(root,'index.html'),'utf8'); - html = html.replace(''); htmlPolicy(html);res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});res.end(html);return; } diff --git a/profile/app.js b/profile/app.js index cc7858d..ff85451 100644 --- a/profile/app.js +++ b/profile/app.js @@ -30,6 +30,7 @@ function saveLanguage() { if (supportedLanguage(requestedLanguage)) saveLanguage(); let current, mode = 'login', message = '', planOpen = false; let welcomeGoal = 'maintain'; +const goalOptions = [['lose','goalLose'],['maintain','goalMaintain'],['gain','goalGain']]; let welcome = true; try { welcome = sessionStorage.getItem('tpt.welcomeSeen') !== '1'; } catch { /* Storage is optional. */ } function closeWelcome(nextMode) { @@ -92,7 +93,7 @@ function field(key,{type='text',min,max,hint}={}) { } function select(key,options) { const node = el('select',{id:'field-'+key,name:key,required:'',...(key==='sex'?{'aria-describedby':'field-sex-hint'}:{})},el('option',{value:''},t(key+'Choose')),options.map(([value,label])=>el('option',{value},t(label)))); - node.value = current?.profile[key] ?? ''; + node.value = current?.profile[key] ?? (key==='goal' ? welcomeGoal : ''); return el('label',{for:'field-'+key},t(key),node,key==='sex'?el('span',{id:'field-sex-hint',class:'hint'},t('sexHint')):null); } function openPlan() { @@ -105,6 +106,7 @@ function planCard() { return el('section',{class:'card','data-plan-card':''}, el('button',{type:'button',class:'primary','data-plan-open':'','aria-describedby':'plan-what',onclick:openPlan},text.button), el('p',{id:'plan-what','data-plan-what':''},text.what), + current ? el('a',{class:'btn',href:'#daily-menu'},t('menuOpen')) : null, !current ? el('p',{class:'hint'},t('planSignin')) : null, !current ? el('button',{type:'button',class:'plan-start','data-plan-start':'',onclick:openPlan},text.start) : null); } @@ -138,7 +140,7 @@ function render() { const goalSelect = el('select',{id:'welcome-goal','aria-describedby':'welcome-goal-note',onchange:event=>{ welcomeGoal=event.target.value; goalNote.textContent=GymPlan.text(lang).welcomeGoal.replace('{goal}',t('goal'+welcomeGoal[0].toUpperCase()+welcomeGoal.slice(1))); - }},...['lose','maintain','gain'].map(value=>el('option',{value},t('goal'+value[0].toUpperCase()+value.slice(1))))); + }},...goalOptions.map(([value,label])=>el('option',{value},t(label)))); goalSelect.value=welcomeGoal; root.append(el('section',{class:'card welcome','aria-labelledby':'welcome-title'}, el('h2',{id:'welcome-title'},t('welcomeTitle')), @@ -155,7 +157,7 @@ function render() { 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('sex',[['male','male'],['female','female']]),select('activity',[['1.2','sedentary'],['1.375','light'],['1.55','moderate'],['1.725','high']]),select('goal',goalOptions)] : [])); 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=>{ @@ -187,12 +189,13 @@ function render() { root.append(form,el('p',{class:'hint'},t('privacy'))); if (current) { const n=current.nutrition; - root.append(el('section',{class:'card'},el('h2',{},t('norm')),el('div',{class:'stats'},el('div',{class:'stat'},el('strong',{},String(n.calories)),t('calories')),el('div',{class:'stat'},el('strong',{},String(n.protein)),t('protein')))),el('section',{class:'card'},el('h2',{},t('menu')),el('p',{},t('menuHint')),n.menu.map(m=>el('article',{class:'meal'},el('h3',{},t(m.name)),el('span',{},`${m.grams} ${t('grams')} · ${m.calories} ${t('calories')} · ${m.protein} ${t('protein')}`)))),el('p',{class:'notice'},t('notice'))); + root.append(el('section',{class:'card'},el('h2',{},t('norm')),el('div',{class:'stats'},el('div',{class:'stat'},el('strong',{},String(n.calories)),t('calories')),el('div',{class:'stat'},el('strong',{},String(n.protein)),t('protein')))),el('section',{class:'card'},el('h2',{id:'daily-menu',tabindex:'-1'},t('menu')),el('p',{},t('menuHint')),n.menu.map(m=>el('article',{class:'meal'},el('h3',{},t(m.name)),el('span',{},`${m.grams} ${t('grams')} · ${m.calories} ${t('calories')} · ${m.protein} ${t('protein')}`)))),el('p',{class:'notice'},t('notice'))); } } root.textContent=t('loading'); try {if (!privateStorageReady) throw new Error('server'); current=await api('profile');}catch(error){if(error.status!==401)message=errorText('server');} render(); +if (location.hash === '#daily-menu') document.getElementById('daily-menu')?.focus(); addEventListener('pageshow',event=>{if(event.persisted) location.reload();}); addEventListener('focus',async()=>{ diff --git a/profile/i18n.json b/profile/i18n.json index b7f313d..1045fb7 100644 --- a/profile/i18n.json +++ b/profile/i18n.json @@ -27,6 +27,7 @@ "calories": "ккал", "protein": "г белка", "menu": "Пример меню на день", + "menuOpen": "Открыть меню на день", "menuHint": "Порции рассчитаны по вашему ориентиру калорий. Состав и пищевая ценность примерные; проверьте продукты на аллергию.", "breakfast": "Завтрак: овсянка с йогуртом", "lunch": "Обед: курица с рисом и овощами", @@ -38,6 +39,7 @@ "passwordHint": "От 12 до 128 символов. Длинный пароль помогает защитить ваш профиль.", "loading": "Загрузка…", "errors": { + "goal": "Не удалось сохранить цель. Выберите цель из списка.", "height": "Рост не подходит. Введите число от 100 до 250 см.", "weight": "Вес не подходит. Введите число от 25 до 350 кг.", "age": "Возраст не подходит. Введите целое число от 18 до 100 лет.", @@ -63,7 +65,7 @@ "loginHeading": "Войдите в свой профиль", "loginIntro": "Введите имя пользователя и пароль. После входа откроются ваши сохранённые данные и ориентир питания.", "registerHeading": "Создайте учётную запись", - "registerIntro": "Выберите имя и пароль, затем заполните данные для расчёта питания. После регистрации откроется ваш профиль.", + "registerIntro": "Выберите имя и пароль и заполните данные о себе. После регистрации вы сможете открыть меню на день и план тренировок.", "toRegister": "Впервые здесь? Создать учётную запись", "toLogin": "Уже есть учётная запись? Войти", "sexChoose": "Выберите пол", @@ -110,6 +112,7 @@ "calories": "ккал", "protein": "г ақуыз", "menu": "Бір күндік мәзір үлгісі", + "menuOpen": "Бір күндік мәзірді ашу", "menuHint": "Үлестер калория бағдарыңызға сай есептелді. Құрамы мен тағамдық құндылығы шамамен берілген; аллергияңызды ескеріңіз.", "breakfast": "Таңғы ас: йогурт қосылған сұлы ботқасы", "lunch": "Түскі ас: күріш пен көкөніс қосылған тауық еті", @@ -121,6 +124,7 @@ "passwordHint": "12–128 таңба. Ұзын құпиясөз профиліңізді қорғауға көмектеседі.", "loading": "Жүктелуде…", "errors": { + "goal": "Мақсат сақталмады. Тізімнен мақсатты таңдаңыз.", "height": "Бойыңыз дұрыс емес. 100–250 см аралығындағы санды енгізіңіз.", "weight": "Салмағыңыз дұрыс емес. 25–350 кг аралығындағы санды енгізіңіз.", "age": "Жасыңыз дұрыс емес. 18–100 аралығындағы бүтін санды енгізіңіз.", @@ -146,7 +150,7 @@ "loginHeading": "Профиліңізге кіріңіз", "loginIntro": "Пайдаланушы аты мен құпиясөзді енгізіңіз. Кіргеннен кейін сақталған деректеріңіз бен тамақтану бағдарыңыз ашылады.", "registerHeading": "Тіркеліңіз", - "registerIntro": "Атыңыз бен құпиясөзді таңдаңыз, содан кейін тамақтануды есептеу үшін деректеріңізді толтырыңыз. Тіркелгеннен кейін профиліңіз ашылады.", + "registerIntro": "Атыңыз бен құпиясөзді таңдаңыз және өзіңіз туралы деректерді толтырыңыз. Тіркелген соң бір күндік мәзір мен жаттығу жоспарын аша аласыз.", "toRegister": "Алғаш рет келдіңіз бе? Тіркелу", "toLogin": "Тіркелгенсіз бе? Кіру", "sexChoose": "Жынысыңызды таңдаңыз", @@ -193,6 +197,7 @@ "calories": "kcal", "protein": "g protein", "menu": "Example daily menu", + "menuOpen": "Open daily menu", "menuHint": "Portions follow your calorie estimate. Ingredients and nutrition are approximate; check for allergens.", "breakfast": "Breakfast: oatmeal with yogurt", "lunch": "Lunch: chicken with rice and vegetables", @@ -204,6 +209,7 @@ "passwordHint": "12–128 characters. A long password helps protect your profile.", "loading": "Loading…", "errors": { + "goal": "Your goal could not be saved. Choose a goal from the list.", "height": "Height is invalid. Enter a number from 100 to 250 cm.", "weight": "Weight is invalid. Enter a number from 25 to 350 kg.", "age": "Age is invalid. Enter a whole number from 18 to 100.", @@ -229,7 +235,7 @@ "loginHeading": "Sign in to your profile", "loginIntro": "Enter your username and password. Your saved details and nutrition estimate will open after you sign in.", "registerHeading": "Create your account", - "registerIntro": "Choose a username and password, then enter your details for a nutrition estimate. Your profile will open after registration.", + "registerIntro": "Choose a username and password and enter your details. After signing up, you can open your daily menu and workout plan.", "toRegister": "New here? Create account", "toLogin": "Already have an account? Sign in", "sexChoose": "Select your sex", -- 2.45.2 From 9c08676f90f9fe6b1bb806444d12377b63ce20d7 Mon Sep 17 00:00:00 2001 From: Peppa Date: Fri, 20 Nov 2026 15:39:27 +0500 Subject: [PATCH 4/5] =?UTF-8?q?TPTIP-83:=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D1=80=D0=B8=D1=82=D1=8C=20=D0=BC=D0=B5=D0=BD=D1=8E=20=D0=B8=20?= =?UTF-8?q?=D0=BF=D0=BB=D0=B0=D0=BD=20=D0=BF=D0=BE=D1=81=D0=BB=D0=B5=20?= =?UTF-8?q?=D1=80=D0=B5=D0=B3=D0=B8=D1=81=D1=82=D1=80=D0=B0=D1=86=D0=B8?= =?UTF-8?q?=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tasks.md | 2 +- profile/app.js | 15 +++++- profile/i18n.json | 6 +-- tests/browser/daily-menu.spec.js | 54 +++++++++++++++++++ tests/profile.test.mjs | 18 ++++++- 5 files changed, 88 insertions(+), 7 deletions(-) create mode 100644 tests/browser/daily-menu.spec.js diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md b/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md index a4118c0..aa3642c 100644 --- a/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md +++ b/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md @@ -5,4 +5,4 @@ ## 2. Проверка -- [ ] 2.1 Проверить результаты и сохранение цели в браузере, запустить проверки проекта и openspec validate. +- [x] 2.1 Проверить результаты и сохранение цели в браузере, запустить проверки проекта и openspec validate. diff --git a/profile/app.js b/profile/app.js index ff85451..fe4aeb6 100644 --- a/profile/app.js +++ b/profile/app.js @@ -92,7 +92,7 @@ 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) { - const node = el('select',{id:'field-'+key,name:key,required:'',...(key==='sex'?{'aria-describedby':'field-sex-hint'}:{})},el('option',{value:''},t(key+'Choose')),options.map(([value,label])=>el('option',{value},t(label)))); + 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 : ''); return el('label',{for:'field-'+key},t(key),node,key==='sex'?el('span',{id:'field-sex-hint',class:'hint'},t('sexHint')):null); } @@ -175,7 +175,18 @@ function render() { if (firstInvalid) {firstInvalid.focus();return;} const body = Object.fromEntries(new FormData(form)); form.setAttribute('aria-busy','true');for (const b of form.querySelectorAll('button')) b.disabled=true; - try { const wasSignedIn=!!current; current=await api(current?'profile':mode,current?'PUT':'POST',body);message=wasSignedIn?t('saved'):'';render(); } + try { + const wasSignedIn=!!current; + current=await api(current?'profile':mode,current?'PUT':'POST',body); + message=wasSignedIn?t('saved'):''; + render(); + if (!wasSignedIn) { + const heading = root.querySelector('h1'); + heading.tabIndex=-1; + heading.focus({preventScroll:true}); + window.scrollTo(0,0); + } + } catch(err) { if (err.status===401 && current) {current=undefined;message=errorText('signin');render();} else {if (measurements.includes(err.message)) showFieldError(form.elements.namedItem(err.message),errorText(err.message));else error.textContent=errorText(mode==='login' && err.message==='credentials'?'loginCredentials':err.message);form.querySelector('[name="'+(Object.hasOwn(body,err.message)?err.message:'username')+'"]')?.focus();} diff --git a/profile/i18n.json b/profile/i18n.json index 1045fb7..1ee40d7 100644 --- a/profile/i18n.json +++ b/profile/i18n.json @@ -22,7 +22,7 @@ "save": "Сохранить и пересчитать", "logout": "Выйти", "saved": "Данные сохранены. Ориентир и порции обновлены.", - "next": "Измените данные и сохраните их: ориентир и порции ниже пересчитаются.", + "next": "Откройте меню на день или план тренировок. Чтобы пересчитать порции, измените данные или цель и сохраните их.", "norm": "Ориентир на день", "calories": "ккал", "protein": "г белка", @@ -107,7 +107,7 @@ "save": "Сақтау және қайта есептеу", "logout": "Шығу", "saved": "Деректер сақталды. Бағдар мен үлестер жаңартылды.", - "next": "Деректерді өзгертіп, сақтаңыз: төмендегі бағдар мен үлестер қайта есептеледі.", + "next": "Бір күндік мәзірді немесе жаттығу жоспарын ашыңыз. Үлестерді қайта есептеу үшін деректеріңізді немесе мақсатыңызды өзгертіп, сақтаңыз.", "norm": "Күндік бағдар", "calories": "ккал", "protein": "г ақуыз", @@ -192,7 +192,7 @@ "save": "Save and recalculate", "logout": "Sign out", "saved": "Details saved. Your estimate and portions have been updated.", - "next": "Edit and save your details to update the estimate and portions below.", + "next": "Open your daily menu or workout plan. To recalculate portions, change your details or goal and save.", "norm": "Daily estimate", "calories": "kcal", "protein": "g protein", diff --git a/tests/browser/daily-menu.spec.js b/tests/browser/daily-menu.spec.js new file mode 100644 index 0000000..03b90a7 --- /dev/null +++ b/tests/browser/daily-menu.spec.js @@ -0,0 +1,54 @@ +const { randomUUID } = require('node:crypto'); +const { test, expect } = require('@playwright/test'); +const translations = require('../../profile/i18n.json'); +const GymPlan = require('../../gym-plan.i18n.js'); + +test.use({ viewport: { width: 360, height: 640 } }); + +for (const lang of ['ru', 'kk', 'en']) { + test(`Меню по выбранной цели и доступ к плану (${lang})`, async ({ page }) => { + const t = translations[lang]; + const plan = GymPlan.text(lang); + const menuLink = page.getByRole('link', { name: t.menuOpen }); + const menuHeading = page.getByRole('heading', { name: t.menu }); + + await page.goto('/?lang=' + lang); + await page.locator('#welcome-goal').selectOption('lose'); + await page.locator('[data-welcome-next]').click(); + await expect(page.getByText(t.registerIntro)).toBeVisible(); + await expect(menuLink).toHaveCount(0); + await expect(menuHeading).toHaveCount(0); + await expect(page.locator('#field-goal')).toHaveValue('lose'); + + const fields = { username: 'menu_' + randomUUID().slice(0, 8), password: 'menu-workout-test-123', height: '175', weight: '75', age: '30' }; + for (const [key, value] of Object.entries(fields)) await page.locator('#field-' + key).fill(value); + await page.locator('#field-sex').selectOption('male'); + await page.locator('#field-activity').selectOption('1.375'); + await page.getByRole('button', { name: t.register, exact: true }).click(); + + const planButton = page.getByRole('button', { name: plan.planHome.button, exact: true }); + await expect(planButton).toBeInViewport(); + await expect(menuLink).toBeInViewport(); + await menuLink.click(); + await expect(menuHeading).toBeInViewport(); + await expect(page.locator('.stats strong').first()).toHaveText('1985'); + await expect(page.locator('.meal h3')).toHaveText([t.breakfast, t.lunch, t.dinner]); + await expect(page.locator('.meal').first()).toContainText(`458 ${t.grams} · 596 ${t.calories}`); + + await page.locator('#field-goal').selectOption('gain'); + await page.getByRole('button', { name: t.save, exact: true }).click(); + await expect(page.locator('.stats strong').first()).toHaveText('2569'); + await page.reload(); + await expect(page.locator('#field-goal')).toHaveValue('gain'); + await expect(page.locator('.meal').first()).toContainText(`593 ${t.grams} · 771 ${t.calories}`); + + await planButton.click(); + await expect(page.getByRole('heading', { name: plan.title })).toBeVisible(); + await expect(page.getByRole('heading', { name: GymPlan.days(lang)[0].name })).toBeVisible(); + await page.goto('/tracker?lang=' + lang); + await expect(menuLink).toBeInViewport(); + await menuLink.click(); + await expect(menuHeading).toBeInViewport(); + await expect(page.locator('.stats strong').first()).toHaveText('2569'); + }); +} diff --git a/tests/profile.test.mjs b/tests/profile.test.mjs index 3a812cf..03d668c 100644 --- a/tests/profile.test.mjs +++ b/tests/profile.test.mjs @@ -8,7 +8,7 @@ import {validateProfile,ProfileService,nutrition} from '../profile/service.mjs'; const profile = {height:182,weight:81,age:32,sex:'male',activity:1.375}; const account = {username:'anna',password:'a-long-private-password',...profile}; test('Пустое или неверное измерение; границы диапазонов',() => { - for (const [key,values] of Object.entries({height:['',null,'abc','1e2',[],true,99,251],weight:['',null,'abc',0,351],age:[17,101,20.5],sex:['','unknown'],activity:['',99]})) { + for (const [key,values] of Object.entries({height:['',null,'abc','1e2',[],true,99,251],weight:['',null,'abc',0,351],age:[17,101,20.5],sex:['','unknown'],activity:['',99],goal:['',null,'unknown']})) { for (const value of values) assert.throws(()=>validateProfile({...profile,[key]:value})); } for (const p of [{height:100,weight:25,age:18},{height:250,weight:350,age:100}]) assert.doesNotThrow(()=>validateProfile({...profile,...p})); @@ -69,3 +69,19 @@ test('Сохранение после перезапуска и истечени now += 8*86400000; assert.throws(()=>service.read(token));service.close(); }); + +test('Ранее созданный профиль без цели и обновление старым клиентом', async () => { + const service = new ProfileService(':memory:'); + try { + const token = await service.authenticate(account,true); + service.db.prepare("UPDATE users SET profile=json_remove(profile,'$.goal')").run(); + assert.equal(service.read(token).profile.goal,'maintain'); + assert.equal(service.read(token).nutrition.calories,2465); + service.update(token,{...profile,goal:'lose'}); + const updated = service.update(token,{...profile,weight:84}); + assert.equal(updated.profile.goal,'lose'); + assert.equal(updated.nutrition.calories,2130); + } finally { + service.close(); + } +}); -- 2.45.2 From b484d0135507b14f8257319bae596470dcd17d48 Mon Sep 17 00:00:00 2001 From: Peppa Date: Fri, 20 Nov 2026 15:39:29 +0500 Subject: [PATCH 5/5] =?UTF-8?q?TPTIP-83:=20=D0=B0=D1=80=D1=85=D0=B8=D0=B2?= =?UTF-8?q?=D0=B8=D1=80=D0=BE=D0=B2=D0=B0=D1=82=D1=8C=20=D0=B8=D0=B7=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B8=20=D0=B7=D0=B0?= =?UTF-8?q?=D0=BF=D0=B8=D1=81=D0=B0=D1=82=D1=8C=20=D1=80=D0=B5=D1=88=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .peppa/memory.md | 2 ++ .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/private-profile/spec.md | 0 .../tasks.md | 0 openspec/specs/private-profile/spec.md | 29 +++++++++++++++++++ 7 files changed, 31 insertions(+) rename openspec/changes/{tptip-83-show-food-and-workout-menu => archive/2026-11-20-tptip-83-show-food-and-workout-menu}/.openspec.yaml (100%) rename openspec/changes/{tptip-83-show-food-and-workout-menu => archive/2026-11-20-tptip-83-show-food-and-workout-menu}/design.md (100%) rename openspec/changes/{tptip-83-show-food-and-workout-menu => archive/2026-11-20-tptip-83-show-food-and-workout-menu}/proposal.md (100%) rename openspec/changes/{tptip-83-show-food-and-workout-menu => archive/2026-11-20-tptip-83-show-food-and-workout-menu}/specs/private-profile/spec.md (100%) rename openspec/changes/{tptip-83-show-food-and-workout-menu => archive/2026-11-20-tptip-83-show-food-and-workout-menu}/tasks.md (100%) diff --git a/.peppa/memory.md b/.peppa/memory.md index 798c845..797a535 100644 --- a/.peppa/memory.md +++ b/.peppa/memory.md @@ -41,6 +41,8 @@ - TPTIP-45: viewSettings при normsPending рассчитывает suggestNorms на «Сохранить» после проверки профиля; последующие ручные нормы сохраняются. tests/browser/skip.spec.js: все разделы, пустые данные, прямое сохранение и reload; CACHE tpt-v24-skip-save. - TPTIP-49: profile/app.js показывает диапазоны и ошибки измерений у полей через validateMeasurement/showFieldError; тексты profile/i18n.json ru/kk/en, браузерная проверка tests/browser/profile-validation.spec.js. - TPTIP-46: шаблон подписи цели welcomeGoal хранится в gym-plan.i18n.js (ru/kk/en); русский мастер подставляет название цели из GOALS. CACHE tpt-v27-clear-goal; проверено 360×640 для всех трёх целей. +- Профиль хранит цель в JSON SQLite, при чтении старых записей подставляет maintain, а прежние клиенты при обновлении без goal сохраняют выбранную цель. + ## Грабли - На 17.11.2026 origin/main содержал только bootstrap, приложение было в task/tptip-8, сервер — в task/tptip-6; task/tptip-5 включает обе зависимости. При объединении server.js и Dockerfile использована версия TPTIP-6. - TPTIP-22: ring(label,fact,target,unit,color) — единица полностью («килокалории/граммы/миллилитры») под названием, внутри кольца «из N»; CACHE sw.js tpt-v5-rings. diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/.openspec.yaml b/openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/.openspec.yaml similarity index 100% rename from openspec/changes/tptip-83-show-food-and-workout-menu/.openspec.yaml rename to openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/.openspec.yaml diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/design.md b/openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/design.md similarity index 100% rename from openspec/changes/tptip-83-show-food-and-workout-menu/design.md rename to openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/design.md diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/proposal.md b/openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/proposal.md similarity index 100% rename from openspec/changes/tptip-83-show-food-and-workout-menu/proposal.md rename to openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/proposal.md diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/specs/private-profile/spec.md b/openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/specs/private-profile/spec.md similarity index 100% rename from openspec/changes/tptip-83-show-food-and-workout-menu/specs/private-profile/spec.md rename to openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/specs/private-profile/spec.md diff --git a/openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md b/openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/tasks.md similarity index 100% rename from openspec/changes/tptip-83-show-food-and-workout-menu/tasks.md rename to openspec/changes/archive/2026-11-20-tptip-83-show-food-and-workout-menu/tasks.md diff --git a/openspec/specs/private-profile/spec.md b/openspec/specs/private-profile/spec.md index bbbaac5..e83f57b 100644 --- a/openspec/specs/private-profile/spec.md +++ b/openspec/specs/private-profile/spec.md @@ -168,3 +168,32 @@ - **WHEN** пользователь входит как anna с паролем wrong-password или как nobody с тем же паролем - **THEN** видит одинаковое сообщение «Имя или пароль не подошли. Проверьте их или создайте учётную запись.» - **AND** профиль недоступен + +### Requirement: Доступ к меню питания и плану тренировок +Система SHALL показывать в профиле и на главной дневника переходы к примеру меню на день и плану тренировок. Пока данные не введены, регистрация SHALL объяснять, как получить результаты. + +#### Scenario: Результаты доступны после регистрации +- **GIVEN** пользователь заполнил имя, пароль, возраст 30, рост 175, вес 75, мужской пол и лёгкую активность +- **WHEN** он создаёт учётную запись +- **THEN** видны переходы «Открыть меню на день» и «План тренировок» +- **AND** в меню указаны завтрак, обед и ужин с порциями + +#### Scenario: Данные ещё не заполнены +- **GIVEN** посетитель без учётной записи видит приветствие +- **WHEN** он нажимает «Далее» +- **THEN** форма предлагает заполнить данные, чтобы увидеть меню и план +- **AND** меню с рассчитанными порциями отсутствует + +### Requirement: Меню с учётом цели +Система SHALL сохранять выбранную цель в профиле и рассчитывать калории и размеры порций по ней. Для профиля без сохранённой цели система SHALL использовать поддержание. + +#### Scenario: Цель «Похудение» применяется к меню +- **GIVEN** пользователь 30 лет, ростом 175 см и весом 75 кг выбрал мужской пол, лёгкую активность и «Похудение» +- **WHEN** он создаёт учётную запись +- **THEN** дневной ориентир составляет 1985 ккал +- **AND** у завтрака указано 596 ккал + +#### Scenario: Ранее созданный профиль без цели +- **GIVEN** у пользователя сохранены возраст 30, рост 175, вес 75, мужской пол и лёгкая активность без цели +- **WHEN** он входит в профиль +- **THEN** выбрано «Поддержание» и дневной ориентир составляет 2336 ккал -- 2.45.2