TPTIP-83: проверить меню и план после регистрации
This commit is contained in:
parent
cbc7a62a91
commit
9c08676f90
@ -5,4 +5,4 @@
|
|||||||
|
|
||||||
## 2. Проверка
|
## 2. Проверка
|
||||||
|
|
||||||
- [ ] 2.1 Проверить результаты и сохранение цели в браузере, запустить проверки проекта и openspec validate.
|
- [x] 2.1 Проверить результаты и сохранение цели в браузере, запустить проверки проекта и openspec validate.
|
||||||
|
|||||||
@ -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);
|
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) {
|
||||||
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 : '');
|
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);
|
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;}
|
if (firstInvalid) {firstInvalid.focus();return;}
|
||||||
const body = Object.fromEntries(new FormData(form));
|
const body = Object.fromEntries(new FormData(form));
|
||||||
form.setAttribute('aria-busy','true');for (const b of form.querySelectorAll('button')) b.disabled=true;
|
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) {
|
catch(err) {
|
||||||
if (err.status===401 && current) {current=undefined;message=errorText('signin');render();}
|
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();}
|
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();}
|
||||||
|
|||||||
@ -22,7 +22,7 @@
|
|||||||
"save": "Сохранить и пересчитать",
|
"save": "Сохранить и пересчитать",
|
||||||
"logout": "Выйти",
|
"logout": "Выйти",
|
||||||
"saved": "Данные сохранены. Ориентир и порции обновлены.",
|
"saved": "Данные сохранены. Ориентир и порции обновлены.",
|
||||||
"next": "Измените данные и сохраните их: ориентир и порции ниже пересчитаются.",
|
"next": "Откройте меню на день или план тренировок. Чтобы пересчитать порции, измените данные или цель и сохраните их.",
|
||||||
"norm": "Ориентир на день",
|
"norm": "Ориентир на день",
|
||||||
"calories": "ккал",
|
"calories": "ккал",
|
||||||
"protein": "г белка",
|
"protein": "г белка",
|
||||||
@ -107,7 +107,7 @@
|
|||||||
"save": "Сақтау және қайта есептеу",
|
"save": "Сақтау және қайта есептеу",
|
||||||
"logout": "Шығу",
|
"logout": "Шығу",
|
||||||
"saved": "Деректер сақталды. Бағдар мен үлестер жаңартылды.",
|
"saved": "Деректер сақталды. Бағдар мен үлестер жаңартылды.",
|
||||||
"next": "Деректерді өзгертіп, сақтаңыз: төмендегі бағдар мен үлестер қайта есептеледі.",
|
"next": "Бір күндік мәзірді немесе жаттығу жоспарын ашыңыз. Үлестерді қайта есептеу үшін деректеріңізді немесе мақсатыңызды өзгертіп, сақтаңыз.",
|
||||||
"norm": "Күндік бағдар",
|
"norm": "Күндік бағдар",
|
||||||
"calories": "ккал",
|
"calories": "ккал",
|
||||||
"protein": "г ақуыз",
|
"protein": "г ақуыз",
|
||||||
@ -192,7 +192,7 @@
|
|||||||
"save": "Save and recalculate",
|
"save": "Save and recalculate",
|
||||||
"logout": "Sign out",
|
"logout": "Sign out",
|
||||||
"saved": "Details saved. Your estimate and portions have been updated.",
|
"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",
|
"norm": "Daily estimate",
|
||||||
"calories": "kcal",
|
"calories": "kcal",
|
||||||
"protein": "g protein",
|
"protein": "g protein",
|
||||||
|
|||||||
54
tests/browser/daily-menu.spec.js
Normal file
54
tests/browser/daily-menu.spec.js
Normal file
@ -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');
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -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 profile = {height:182,weight:81,age:32,sex:'male',activity:1.375};
|
||||||
const account = {username:'anna',password:'a-long-private-password',...profile};
|
const account = {username:'anna',password:'a-long-private-password',...profile};
|
||||||
test('Пустое или неверное измерение; границы диапазонов',() => {
|
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 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}));
|
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;
|
now += 8*86400000;
|
||||||
assert.throws(()=>service.read(token));service.close();
|
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();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user