TPTIP-89: добавить расчёт меню и тренировок до входа

This commit is contained in:
peppa-bot 2026-11-25 12:43:53 +00:00
parent 24849c890c
commit 1df242e681
12 changed files with 240 additions and 70 deletions

View File

@ -69,3 +69,5 @@
| Меню и упражнения по цели | Создать меню и план тренировок, Меню и план тренировок, Пример меню на каждый день, подходы, повторения | генерация, сет | Результат в профиле. До расчёта указываем, какие данные нужно заполнить |
| Экран дневника за день | Сегодня, + Еда, + Тренировка, + Вода | — | Вкладка открывает выбранный день. Кнопка воды добавляет 250 мл |
| Расчёт до входа | Создать меню и план тренировок, Назад | — | Возраст, рост, вес, пол для расчёта, активность и цель используются на открытой странице |

View File

@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-11-25

View File

@ -0,0 +1,15 @@
# Design
## Context
Расчёт для профиля и проверка измерений находятся в серверном модуле. Карточка профиля уже показывает меню и упражнения по цели.
## Decisions
- Открывать форму из приветствия и экрана входа. Переносить выбранную на приветствии цель и давать изменить её в форме.
- Вынести чистый расчёт с проверкой данных в общий модуль для браузера и сервера. Значения формы и результат держать в памяти страницы, расчёт выполняется на устройстве пользователя.
- Использовать существующие поля, упражнения, порции и переводы. После редактирования нужно нажать кнопку расчёта снова.
## Risks / Trade-offs
Общий модуль должен отдаваться основным сервером. Проверка браузером проходит через входную страницу настоящего сервера.

View File

@ -0,0 +1,27 @@
# Proposal
[TPTIP-89](https://peppa.telecom.quest) — дать пользователю рассчитать меню и план тренировок до входа.
## Why
На первом экране можно выбрать цель, но расчёт доступен только после создания учётной записи.
## What Changes
- Добавить кнопку «Создать меню и план тренировок» на приветствии и экране входа.
- Открывать отдельную форму с возрастом, ростом, весом, полом для расчёта, активностью и целью.
- После заполнения показывать пример меню с порциями и четыре дня тренировок.
## Capabilities
### New Capabilities
- `public-menu-plan` — расчёт меню и плана тренировок без входа.
## Impact
Публичный экран, переводы, общий расчёт питания и браузерная проверка. Создание учётной записи и сохранение плана вне задачи.
## Открытые вопросы
Нет.

View File

@ -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** результат не показан

View File

@ -0,0 +1,8 @@
## 1. Форма и расчёт
- [x] 1.1 Открыть публичную форму из приветствия и экрана входа, добавить тексты на русском, казахском и английском.
- [x] 1.2 Подключить общий расчёт и показать порции и четыре дня тренировок.
## 2. Проверка
- [ ] 2.1 Проверить в браузере расчёт и ошибку ввода до входа, запустить проверки проекта и `openspec validate`.

View File

@ -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'));

View File

@ -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 {

View File

@ -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)",

34
profile/nutrition.mjs Normal file
View File

@ -0,0 +1,34 @@
export class InputError extends Error {
constructor(key, status = 400) { super(key); this.status = status; }
}
const goalFactors = {lose: 0.85, maintain: 1, gain: 1.1};
export function validateProfile(input, defaultGoal = 'maintain') {
const out = {};
for (const [key, min, max] of [['height',100,250],['weight',25,350],['age',18,100]]) {
const value = input[key];
if (!['number','string'].includes(typeof value) || !/^\d+(?:[.,]\d+)?$/.test(String(value))) throw new InputError(key);
out[key] = Number(String(value).replace(',', '.'));
if (!Number.isFinite(out[key]) || out[key] < min || out[key] > max) throw new InputError(key);
}
if (!Number.isInteger(out.age)) throw new InputError('age');
if (!['male','female'].includes(input.sex)) throw new InputError('sex');
out.sex = input.sex;
if (!['1.2','1.375','1.55','1.725'].includes(String(input.activity))) throw new InputError('activity');
out.activity = Number(input.activity);
const goal = input.goal === undefined ? defaultGoal : input.goal;
if (typeof goal !== 'string' || !Object.hasOwn(goalFactors,goal)) throw new InputError('goal');
out.goal = goal;
return out;
}
export function nutrition(profile) {
const p = validateProfile(profile);
const calories = Math.round((10*p.weight + 6.25*p.height - 5*p.age + (p.sex === 'male' ? 5 : -161))*p.activity*goalFactors[p.goal]);
const protein = Math.round(p.weight*1.6);
// One illustrative day: proportions sum to the daily energy estimate.
const menu = [
{ name: 'breakfast', share: .3, kcal100: 130, protein100: 7 },
{ name: 'lunch', share: .4, kcal100: 150, protein100: 12 },
{ name: 'dinner', share: .3, kcal100: 140, protein100: 11 },
].map(m => ({name:m.name, grams: Math.round(calories*m.share/m.kcal100*100), calories: Math.round(calories*m.share), protein: Math.round(calories*m.share/m.kcal100*m.protein100)}));
return { calories, protein, menu };
}

View File

@ -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()} = {}) {

View File

@ -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}