From 9c08676f90f9fe6b1bb806444d12377b63ce20d7 Mon Sep 17 00:00:00 2001 From: Peppa Date: Fri, 20 Nov 2026 15:39:27 +0500 Subject: [PATCH] =?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(); + } +});