Compare commits
1 Commits
main
...
task/tptip
| Author | SHA1 | Date | |
|---|---|---|---|
| ae1cfeff7e |
@ -41,8 +41,6 @@
|
|||||||
- TPTIP-45: viewSettings при normsPending рассчитывает suggestNorms на «Сохранить» после проверки профиля; последующие ручные нормы сохраняются. tests/browser/skip.spec.js: все разделы, пустые данные, прямое сохранение и reload; CACHE tpt-v24-skip-save.
|
- 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-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 для всех трёх целей.
|
- 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.
|
- На 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.
|
- TPTIP-22: ring(label,fact,target,unit,color) — единица полностью («килокалории/граммы/миллилитры») под названием, внутри кольца «из N»; CACHE sw.js tpt-v5-rings.
|
||||||
@ -78,4 +76,3 @@
|
|||||||
|
|
||||||
- TPTIP-63: tests/browser/russian-browser-auth.spec.js проверяет ru-RU, русские подсказки, EN→RU и reload без моков; перевод уже в main.
|
- 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-65: ошибки credentials при login отображаются через loginCredentials (ru/kk/en); регистрация сохраняет общий credentials. tests/browser/password-guidance.spec.js проверяет реальные неверный пароль и неизвестное имя.
|
||||||
- TPTIP-1: блюдо дня зависит от даты; для теста с фото выбирайте овсянку через «+ Рецепт».
|
|
||||||
|
|||||||
@ -63,5 +63,3 @@
|
|||||||
|
|
||||||
| Длина пароля | От 12 до 128 символов. Длинный пароль помогает защитить ваш профиль. | сложность пароля | Подсказка под полем пароля |
|
| Длина пароля | От 12 до 128 символов. Длинный пароль помогает защитить ваш профиль. | сложность пароля | Подсказка под полем пароля |
|
||||||
| Ошибка входа | Имя или пароль не подошли. Проверьте их или создайте учётную запись. | имя не существует, неверный пароль | Одинаковое сообщение при неверном имени и пароле |
|
| Ошибка входа | Имя или пароль не подошли. Проверьте их или создайте учётную запись. | имя не существует, неверный пароль | Одинаковое сообщение при неверном имени и пароле |
|
||||||
|
|
||||||
| Переход к рассчитанному меню | Открыть меню на день | — | Показывает пример меню с порциями для выбранной цели |
|
|
||||||
|
|||||||
@ -445,7 +445,6 @@ function applyPrivateProfile() {
|
|||||||
const personal = window.TPTProfile;
|
const personal = window.TPTProfile;
|
||||||
delete db.settings.normsPending;
|
delete db.settings.normsPending;
|
||||||
db.settings.profile = { ...personal.profile, sex: personal.profile.sex === 'male' ? 'm' : 'f' };
|
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 });
|
Object.assign(db.settings, suggestNorms(db.settings.goal, db.settings.profile), { onboarded: true });
|
||||||
db.settings.kcal = personal.nutrition.calories;
|
db.settings.kcal = personal.nutrition.calories;
|
||||||
db.settings.protein = personal.nutrition.protein;
|
db.settings.protein = personal.nutrition.protein;
|
||||||
@ -722,11 +721,10 @@ function viewToday() {
|
|||||||
return h('div', null, dateNav(),
|
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('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),
|
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))),
|
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, 'Дневные нормы пока не рассчитаны'),
|
s.normsPending ? h('div', { class: 'card', 'data-norms-pending': '' }, h('b', null, 'Дневные нормы пока не рассчитаны'),
|
||||||
h('p', { class: 'small muted', style: 'margin:6px 0 8px' }, 'Сейчас показаны примерные цифры. Укажите возраст, рост и вес в «Настройках» — и нормы станут вашими.'),
|
h('p', { class: 'small muted', style: 'margin:6px 0 8px' }, 'Для расчёта норм нужны возраст, рост и вес. Сейчас показаны примерные цифры: укажите данные в «Настройках» — и нормы станут вашими.'),
|
||||||
h('button', { class: 'primary', 'data-norms-open': '', onclick: goSettings }, 'Открыть «Настройки»')) : null,
|
h('button', { class: 'primary', 'data-norms-open': '', onclick: goSettings }, 'Перейти в Настройки')) : null,
|
||||||
h('div', { class: 'card' },
|
h('div', { class: 'card' },
|
||||||
h('p', { class: 'small muted rings-cap', 'data-rings-caption': '' }, 'Съедено из дневной нормы'),
|
h('p', { class: 'small muted rings-cap', 'data-rings-caption': '' }, 'Съедено из дневной нормы'),
|
||||||
h('div', { class: 'rings' },
|
h('div', { class: 'rings' },
|
||||||
|
|||||||
@ -1,3 +0,0 @@
|
|||||||
schema: spec-driven
|
|
||||||
created: 2026-11-18
|
|
||||||
skip_specs: true
|
|
||||||
@ -1,3 +0,0 @@
|
|||||||
# Design
|
|
||||||
|
|
||||||
Заголовок TPTIP-1 трактуем как готовую идею блюда на день и готовую программу занятий. Эти возможности уже доставлены в основном приложении. Проверяем их вместе через регистрацию и защищённый дневник на телефоне. Тест проходит через обычное сохранение блюда и тренировки, затем повторно открывает дневник. База профилей для прогона изолируется через DATA_DIR.
|
|
||||||
@ -1,22 +0,0 @@
|
|||||||
# TPTIP-1 — Меню питания и тренировок
|
|
||||||
|
|
||||||
## Why
|
|
||||||
|
|
||||||
Пользователю нужны готовая идея блюда на день и план занятий, с которых можно начать вести дневник.
|
|
||||||
|
|
||||||
## What Changes
|
|
||||||
|
|
||||||
- Проверить выбор готового блюда и повторное открытие записанного блюда.
|
|
||||||
- Проверить просмотр четырёх дней готового плана и сохранение занятия из плана.
|
|
||||||
|
|
||||||
## Capabilities
|
|
||||||
|
|
||||||
Требования уже описаны в `tracker` и `home-plan-button`. Изменение добавляет сквозную проверку этих возможностей.
|
|
||||||
|
|
||||||
## Impact
|
|
||||||
|
|
||||||
Браузерная проверка на маршрутах рабочего приложения. Персональный подбор диеты, новая программа упражнений и изменение расчёта норм вне объёма задачи.
|
|
||||||
|
|
||||||
## Вопросы к PM
|
|
||||||
|
|
||||||
Нет.
|
|
||||||
@ -1,5 +0,0 @@
|
|||||||
## 1. Проверка меню питания и тренировок
|
|
||||||
|
|
||||||
- [x] 1.1 Сверить возможности основного приложения с действующими спецификациями.
|
|
||||||
- [x] 1.2 Проверить на телефоне выбор блюда и сохранение тренировки из готового плана в одном профиле.
|
|
||||||
- [x] 1.3 Выполнить проверки проекта.
|
|
||||||
@ -1,2 +0,0 @@
|
|||||||
schema: spec-driven
|
|
||||||
created: 2026-11-20
|
|
||||||
@ -1,19 +0,0 @@
|
|||||||
# Design
|
|
||||||
|
|
||||||
## Context
|
|
||||||
|
|
||||||
Профиль хранится в SQLite как JSON. Публичное приветствие держит цель до регистрации. Дневник получает сохранённый профиль с сервера.
|
|
||||||
|
|
||||||
## Goals / Non-Goals
|
|
||||||
|
|
||||||
Показать меню и план после регистрации, из профиля и дневника. Сохранить существующий набор блюд и готовый план.
|
|
||||||
|
|
||||||
## Decisions
|
|
||||||
|
|
||||||
- Сохраняем цель в JSON профиля. Для записей без цели используем поддержание. Запрос редактирования без цели сохраняет прежний выбор.
|
|
||||||
- Применяем множители из дневника (0,85 / 1 / 1,10) до расчёта порций. Расчёт белка остаётся прежним. Дневник использует цель профиля для остальных норм.
|
|
||||||
- Переход к меню ведёт к заголовку результата в профиле. План открывается по существующему адресу дневника с выбранным языком. До регистрации форма поясняет, когда появится результат.
|
|
||||||
|
|
||||||
## Risks / Trade-offs
|
|
||||||
|
|
||||||
Узкий экран требует проверить доступность обоих переходов без прокрутки. Старые профили и клиенты проверяем отдельно.
|
|
||||||
@ -1,25 +0,0 @@
|
|||||||
[TPTIP-83](https://peppa.telecom.quest) — сделать меню питания на день и план тренировок доступными после заполнения профиля.
|
|
||||||
|
|
||||||
## Why
|
|
||||||
|
|
||||||
Пример меню находится ниже формы профиля, а цель с приветствия не влияет на порции. Пользователю нужен прямой переход к обоим результатам.
|
|
||||||
|
|
||||||
## What Changes
|
|
||||||
|
|
||||||
- Показать переходы к меню питания и плану тренировок вверху профиля и на главной дневника.
|
|
||||||
- Сохранить выбранную цель и учесть её при расчёте калорий и порций.
|
|
||||||
- До расчёта объяснить, куда ввести данные.
|
|
||||||
|
|
||||||
## Capabilities
|
|
||||||
|
|
||||||
### Modified Capabilities
|
|
||||||
|
|
||||||
- `private-profile` — доступ к результатам и расчёт меню по цели.
|
|
||||||
|
|
||||||
## Impact
|
|
||||||
|
|
||||||
Формы профиля, дневник, локализация и расчёт на сервере. Вне задачи создание новых рецептов и индивидуальных тренировок.
|
|
||||||
|
|
||||||
## Вопросы к PM
|
|
||||||
|
|
||||||
Нет.
|
|
||||||
@ -1,30 +0,0 @@
|
|||||||
## 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 ккал
|
|
||||||
@ -1,8 +0,0 @@
|
|||||||
## 1. Реализация
|
|
||||||
|
|
||||||
- [x] 1.1 Сохранить цель в профиле и применить её к расчёту и дневным нормам.
|
|
||||||
- [x] 1.2 Добавить переход к меню из профиля и дневника, сохранить переход к плану и перевести подсказку регистрации.
|
|
||||||
|
|
||||||
## 2. Проверка
|
|
||||||
|
|
||||||
- [x] 2.1 Проверить результаты и сохранение цели в браузере, запустить проверки проекта и openspec validate.
|
|
||||||
@ -1 +0,0 @@
|
|||||||
Код не меняется: profile/i18n.json (sexChoose, sexHint, toLogin) уже покрывает требования. Решение: только тест tests/browser/register-sex.spec.js.
|
|
||||||
@ -1,4 +0,0 @@
|
|||||||
## Why
|
|
||||||
Нужно убедиться, что на экране регистрации выбор пола понятен без объяснений.
|
|
||||||
## What Changes
|
|
||||||
Поведение уже реализовано в TPTIP-50 (подсказка «Выберите пол», пояснение у поля, кнопка возврата ко входу). Добавляется отдельная браузерная проверка на ru/kk/en.
|
|
||||||
@ -1,14 +0,0 @@
|
|||||||
## ADDED Requirements
|
|
||||||
### Requirement: Понятный выбор пола при регистрации
|
|
||||||
Форма регистрации SHALL показывать подсказку «Выберите пол», пояснение зачем нужен пол и возврат ко входу.
|
|
||||||
|
|
||||||
#### Scenario: Экран регистрации
|
|
||||||
- **GIVEN** пользователь на экране входа
|
|
||||||
- **WHEN** он нажимает «Создать аккаунт»
|
|
||||||
- **THEN** первая строка списка пола — «Выберите пол»
|
|
||||||
- **AND** рядом написано, что пол нужен для оценки калорий
|
|
||||||
|
|
||||||
#### Scenario: Возврат ко входу
|
|
||||||
- **GIVEN** открыта форма регистрации
|
|
||||||
- **WHEN** пользователь нажимает «Уже есть учётная запись? Войти»
|
|
||||||
- **THEN** открывается форма входа без поля пола
|
|
||||||
@ -1,2 +0,0 @@
|
|||||||
- [x] 1. Проверить, что подсказка, пояснение и возврат ко входу уже есть
|
|
||||||
- [x] 2. Добавить tests/browser/register-sex.spec.js (ru/kk/en)
|
|
||||||
1
openspec/changes/tptip-71-norms-hint/design.md
Normal file
1
openspec/changes/tptip-71-norms-hint/design.md
Normal file
@ -0,0 +1 @@
|
|||||||
|
Решение: меняем только тексты карточки [data-norms-pending]; пересчёт норм и ошибки у полей уже работают (TPTIP-42/45/49). CACHE tpt-v28-norms-hint.
|
||||||
5
openspec/changes/tptip-71-norms-hint/proposal.md
Normal file
5
openspec/changes/tptip-71-norms-hint/proposal.md
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
## Why
|
||||||
|
После «Пропустить» нужно простыми словами сказать, что для норм нужны возраст, рост и вес, и дать кнопку «Перейти в Настройки».
|
||||||
|
|
||||||
|
## What Changes
|
||||||
|
- Текст подсказки и кнопка на главной уточнены.
|
||||||
@ -0,0 +1,14 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
### Requirement: Подсказка про данные для норм
|
||||||
|
После «Пропустить» главный экран SHALL объяснять, что для расчёта норм нужны возраст, рост и вес, и давать кнопку «Перейти в Настройки».
|
||||||
|
|
||||||
|
#### Scenario: Подсказка после пропуска
|
||||||
|
- **GIVEN** пользователь нажал «Пропустить»
|
||||||
|
- **WHEN** открыт главный экран
|
||||||
|
- **THEN** видно «Для расчёта норм нужны возраст, рост и вес»
|
||||||
|
- **AND** есть кнопка «Перейти в Настройки»
|
||||||
|
|
||||||
|
#### Scenario: Неверные данные
|
||||||
|
- **GIVEN** открыты «Настройки» после пропуска
|
||||||
|
- **WHEN** пользователь вводит рост 5 и сохраняет
|
||||||
|
- **THEN** рядом с полем понятное сообщение по-русски
|
||||||
3
openspec/changes/tptip-71-norms-hint/tasks.md
Normal file
3
openspec/changes/tptip-71-norms-hint/tasks.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
## 1. Реализация
|
||||||
|
- [x] 1.1 Уточнить текст и кнопку карточки
|
||||||
|
- [x] 1.2 Обновить тесты, CACHE
|
||||||
@ -168,32 +168,3 @@
|
|||||||
- **WHEN** пользователь входит как anna с паролем wrong-password или как nobody с тем же паролем
|
- **WHEN** пользователь входит как anna с паролем wrong-password или как nobody с тем же паролем
|
||||||
- **THEN** видит одинаковое сообщение «Имя или пароль не подошли. Проверьте их или создайте учётную запись.»
|
- **THEN** видит одинаковое сообщение «Имя или пароль не подошли. Проверьте их или создайте учётную запись.»
|
||||||
- **AND** профиль недоступен
|
- **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 ккал
|
|
||||||
|
|||||||
@ -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; }
|
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 lang = new URL(req.url,'http://localhost').searchParams.get('lang');
|
||||||
const dictionaries = JSON.parse(await readFile(resolve(root,'profile/i18n.json'),'utf8'));
|
const dictionaries = JSON.parse(await readFile(resolve(root,'profile/i18n.json'),'utf8'));
|
||||||
const text = Object.hasOwn(dictionaries,lang) ? dictionaries[lang] : dictionaries.ru;
|
const text = (dictionaries[lang] || dictionaries.ru).profile;
|
||||||
let html = await readFile(resolve(root,'index.html'),'utf8');
|
let html = await readFile(resolve(root,'index.html'),'utf8');
|
||||||
html = html.replace('<script>',`<script>window.TPTProfile=${JSON.stringify(personal)};window.TPTProfileText=${JSON.stringify(text.profile)};window.TPTMenuText=${JSON.stringify(text.menuOpen)};</script><script>`);
|
html = html.replace('<script>',`<script>window.TPTProfile=${JSON.stringify(personal)};window.TPTProfileText=${JSON.stringify(text)};</script><script>`);
|
||||||
html = html.replace('</body>','<script type="module" src="/profile/tracker-guard.js"></script></body>');
|
html = html.replace('</body>','<script type="module" src="/profile/tracker-guard.js"></script></body>');
|
||||||
htmlPolicy(html);res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});res.end(html);return;
|
htmlPolicy(html);res.writeHead(200,{'Content-Type':'text/html; charset=utf-8'});res.end(html);return;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -30,7 +30,6 @@ function saveLanguage() {
|
|||||||
if (supportedLanguage(requestedLanguage)) saveLanguage();
|
if (supportedLanguage(requestedLanguage)) saveLanguage();
|
||||||
let current, mode = 'login', message = '', planOpen = false;
|
let current, mode = 'login', message = '', planOpen = false;
|
||||||
let welcomeGoal = 'maintain';
|
let welcomeGoal = 'maintain';
|
||||||
const goalOptions = [['lose','goalLose'],['maintain','goalMaintain'],['gain','goalGain']];
|
|
||||||
let welcome = true;
|
let welcome = true;
|
||||||
try { welcome = sessionStorage.getItem('tpt.welcomeSeen') !== '1'; } catch { /* Storage is optional. */ }
|
try { welcome = sessionStorage.getItem('tpt.welcomeSeen') !== '1'; } catch { /* Storage is optional. */ }
|
||||||
function closeWelcome(nextMode) {
|
function closeWelcome(nextMode) {
|
||||||
@ -92,8 +91,8 @@ 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'}:{})},key==='goal'?null: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'}:{})},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] ?? '';
|
||||||
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);
|
||||||
}
|
}
|
||||||
function openPlan() {
|
function openPlan() {
|
||||||
@ -106,7 +105,6 @@ function planCard() {
|
|||||||
return el('section',{class:'card','data-plan-card':''},
|
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('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),
|
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('p',{class:'hint'},t('planSignin')) : null,
|
||||||
!current ? el('button',{type:'button',class:'plan-start','data-plan-start':'',onclick:openPlan},text.start) : null);
|
!current ? el('button',{type:'button',class:'plan-start','data-plan-start':'',onclick:openPlan},text.start) : null);
|
||||||
}
|
}
|
||||||
@ -140,7 +138,7 @@ function render() {
|
|||||||
const goalSelect = el('select',{id:'welcome-goal','aria-describedby':'welcome-goal-note',onchange:event=>{
|
const goalSelect = el('select',{id:'welcome-goal','aria-describedby':'welcome-goal-note',onchange:event=>{
|
||||||
welcomeGoal=event.target.value;
|
welcomeGoal=event.target.value;
|
||||||
goalNote.textContent=GymPlan.text(lang).welcomeGoal.replace('{goal}',t('goal'+welcomeGoal[0].toUpperCase()+welcomeGoal.slice(1)));
|
goalNote.textContent=GymPlan.text(lang).welcomeGoal.replace('{goal}',t('goal'+welcomeGoal[0].toUpperCase()+welcomeGoal.slice(1)));
|
||||||
}},...goalOptions.map(([value,label])=>el('option',{value},t(label))));
|
}},...['lose','maintain','gain'].map(value=>el('option',{value},t('goal'+value[0].toUpperCase()+value.slice(1)))));
|
||||||
goalSelect.value=welcomeGoal;
|
goalSelect.value=welcomeGoal;
|
||||||
root.append(el('section',{class:'card welcome','aria-labelledby':'welcome-title'},
|
root.append(el('section',{class:'card welcome','aria-labelledby':'welcome-title'},
|
||||||
el('h2',{id:'welcome-title'},t('welcomeTitle')),
|
el('h2',{id:'welcome-title'},t('welcomeTitle')),
|
||||||
@ -157,7 +155,7 @@ function render() {
|
|||||||
const inputs = el('div',{class:'grid'},
|
const inputs = el('div',{class:'grid'},
|
||||||
!current?field('username',{hint:'usernameHint'}):null,!current?field('password',{type:'password',hint:'passwordHint'}):null,
|
!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'}),
|
...(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)] : []));
|
select('sex',[['male','male'],['female','female']]),select('activity',[['1.2','sedentary'],['1.375','light'],['1.55','moderate'],['1.725','high']])] : []));
|
||||||
const submit = el('button',{class:'primary',type:'submit'},t(current?'save':mode));
|
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));
|
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=>{
|
form.addEventListener('submit',async e=>{
|
||||||
@ -175,18 +173,7 @@ 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 {
|
try { const wasSignedIn=!!current; current=await api(current?'profile':mode,current?'PUT':'POST',body);message=wasSignedIn?t('saved'):'';render(); }
|
||||||
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();}
|
||||||
@ -200,13 +187,12 @@ function render() {
|
|||||||
root.append(form,el('p',{class:'hint'},t('privacy')));
|
root.append(form,el('p',{class:'hint'},t('privacy')));
|
||||||
if (current) {
|
if (current) {
|
||||||
const n=current.nutrition;
|
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',{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.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.textContent=t('loading');
|
root.textContent=t('loading');
|
||||||
try {if (!privateStorageReady) throw new Error('server'); current=await api('profile');}catch(error){if(error.status!==401)message=errorText('server');}
|
try {if (!privateStorageReady) throw new Error('server'); current=await api('profile');}catch(error){if(error.status!==401)message=errorText('server');}
|
||||||
render();
|
render();
|
||||||
if (location.hash === '#daily-menu') document.getElementById('daily-menu')?.focus();
|
|
||||||
|
|
||||||
addEventListener('pageshow',event=>{if(event.persisted) location.reload();});
|
addEventListener('pageshow',event=>{if(event.persisted) location.reload();});
|
||||||
addEventListener('focus',async()=>{
|
addEventListener('focus',async()=>{
|
||||||
|
|||||||
@ -22,12 +22,11 @@
|
|||||||
"save": "Сохранить и пересчитать",
|
"save": "Сохранить и пересчитать",
|
||||||
"logout": "Выйти",
|
"logout": "Выйти",
|
||||||
"saved": "Данные сохранены. Ориентир и порции обновлены.",
|
"saved": "Данные сохранены. Ориентир и порции обновлены.",
|
||||||
"next": "Откройте меню на день или план тренировок. Чтобы пересчитать порции, измените данные или цель и сохраните их.",
|
"next": "Измените данные и сохраните их: ориентир и порции ниже пересчитаются.",
|
||||||
"norm": "Ориентир на день",
|
"norm": "Ориентир на день",
|
||||||
"calories": "ккал",
|
"calories": "ккал",
|
||||||
"protein": "г белка",
|
"protein": "г белка",
|
||||||
"menu": "Пример меню на день",
|
"menu": "Пример меню на день",
|
||||||
"menuOpen": "Открыть меню на день",
|
|
||||||
"menuHint": "Порции рассчитаны по вашему ориентиру калорий. Состав и пищевая ценность примерные; проверьте продукты на аллергию.",
|
"menuHint": "Порции рассчитаны по вашему ориентиру калорий. Состав и пищевая ценность примерные; проверьте продукты на аллергию.",
|
||||||
"breakfast": "Завтрак: овсянка с йогуртом",
|
"breakfast": "Завтрак: овсянка с йогуртом",
|
||||||
"lunch": "Обед: курица с рисом и овощами",
|
"lunch": "Обед: курица с рисом и овощами",
|
||||||
@ -39,7 +38,6 @@
|
|||||||
"passwordHint": "От 12 до 128 символов. Длинный пароль помогает защитить ваш профиль.",
|
"passwordHint": "От 12 до 128 символов. Длинный пароль помогает защитить ваш профиль.",
|
||||||
"loading": "Загрузка…",
|
"loading": "Загрузка…",
|
||||||
"errors": {
|
"errors": {
|
||||||
"goal": "Не удалось сохранить цель. Выберите цель из списка.",
|
|
||||||
"height": "Рост не подходит. Введите число от 100 до 250 см.",
|
"height": "Рост не подходит. Введите число от 100 до 250 см.",
|
||||||
"weight": "Вес не подходит. Введите число от 25 до 350 кг.",
|
"weight": "Вес не подходит. Введите число от 25 до 350 кг.",
|
||||||
"age": "Возраст не подходит. Введите целое число от 18 до 100 лет.",
|
"age": "Возраст не подходит. Введите целое число от 18 до 100 лет.",
|
||||||
@ -65,7 +63,7 @@
|
|||||||
"loginHeading": "Войдите в свой профиль",
|
"loginHeading": "Войдите в свой профиль",
|
||||||
"loginIntro": "Введите имя пользователя и пароль. После входа откроются ваши сохранённые данные и ориентир питания.",
|
"loginIntro": "Введите имя пользователя и пароль. После входа откроются ваши сохранённые данные и ориентир питания.",
|
||||||
"registerHeading": "Создайте учётную запись",
|
"registerHeading": "Создайте учётную запись",
|
||||||
"registerIntro": "Выберите имя и пароль и заполните данные о себе. После регистрации вы сможете открыть меню на день и план тренировок.",
|
"registerIntro": "Выберите имя и пароль, затем заполните данные для расчёта питания. После регистрации откроется ваш профиль.",
|
||||||
"toRegister": "Впервые здесь? Создать учётную запись",
|
"toRegister": "Впервые здесь? Создать учётную запись",
|
||||||
"toLogin": "Уже есть учётная запись? Войти",
|
"toLogin": "Уже есть учётная запись? Войти",
|
||||||
"sexChoose": "Выберите пол",
|
"sexChoose": "Выберите пол",
|
||||||
@ -107,12 +105,11 @@
|
|||||||
"save": "Сақтау және қайта есептеу",
|
"save": "Сақтау және қайта есептеу",
|
||||||
"logout": "Шығу",
|
"logout": "Шығу",
|
||||||
"saved": "Деректер сақталды. Бағдар мен үлестер жаңартылды.",
|
"saved": "Деректер сақталды. Бағдар мен үлестер жаңартылды.",
|
||||||
"next": "Бір күндік мәзірді немесе жаттығу жоспарын ашыңыз. Үлестерді қайта есептеу үшін деректеріңізді немесе мақсатыңызды өзгертіп, сақтаңыз.",
|
"next": "Деректерді өзгертіп, сақтаңыз: төмендегі бағдар мен үлестер қайта есептеледі.",
|
||||||
"norm": "Күндік бағдар",
|
"norm": "Күндік бағдар",
|
||||||
"calories": "ккал",
|
"calories": "ккал",
|
||||||
"protein": "г ақуыз",
|
"protein": "г ақуыз",
|
||||||
"menu": "Бір күндік мәзір үлгісі",
|
"menu": "Бір күндік мәзір үлгісі",
|
||||||
"menuOpen": "Бір күндік мәзірді ашу",
|
|
||||||
"menuHint": "Үлестер калория бағдарыңызға сай есептелді. Құрамы мен тағамдық құндылығы шамамен берілген; аллергияңызды ескеріңіз.",
|
"menuHint": "Үлестер калория бағдарыңызға сай есептелді. Құрамы мен тағамдық құндылығы шамамен берілген; аллергияңызды ескеріңіз.",
|
||||||
"breakfast": "Таңғы ас: йогурт қосылған сұлы ботқасы",
|
"breakfast": "Таңғы ас: йогурт қосылған сұлы ботқасы",
|
||||||
"lunch": "Түскі ас: күріш пен көкөніс қосылған тауық еті",
|
"lunch": "Түскі ас: күріш пен көкөніс қосылған тауық еті",
|
||||||
@ -124,7 +121,6 @@
|
|||||||
"passwordHint": "12–128 таңба. Ұзын құпиясөз профиліңізді қорғауға көмектеседі.",
|
"passwordHint": "12–128 таңба. Ұзын құпиясөз профиліңізді қорғауға көмектеседі.",
|
||||||
"loading": "Жүктелуде…",
|
"loading": "Жүктелуде…",
|
||||||
"errors": {
|
"errors": {
|
||||||
"goal": "Мақсат сақталмады. Тізімнен мақсатты таңдаңыз.",
|
|
||||||
"height": "Бойыңыз дұрыс емес. 100–250 см аралығындағы санды енгізіңіз.",
|
"height": "Бойыңыз дұрыс емес. 100–250 см аралығындағы санды енгізіңіз.",
|
||||||
"weight": "Салмағыңыз дұрыс емес. 25–350 кг аралығындағы санды енгізіңіз.",
|
"weight": "Салмағыңыз дұрыс емес. 25–350 кг аралығындағы санды енгізіңіз.",
|
||||||
"age": "Жасыңыз дұрыс емес. 18–100 аралығындағы бүтін санды енгізіңіз.",
|
"age": "Жасыңыз дұрыс емес. 18–100 аралығындағы бүтін санды енгізіңіз.",
|
||||||
@ -150,7 +146,7 @@
|
|||||||
"loginHeading": "Профиліңізге кіріңіз",
|
"loginHeading": "Профиліңізге кіріңіз",
|
||||||
"loginIntro": "Пайдаланушы аты мен құпиясөзді енгізіңіз. Кіргеннен кейін сақталған деректеріңіз бен тамақтану бағдарыңыз ашылады.",
|
"loginIntro": "Пайдаланушы аты мен құпиясөзді енгізіңіз. Кіргеннен кейін сақталған деректеріңіз бен тамақтану бағдарыңыз ашылады.",
|
||||||
"registerHeading": "Тіркеліңіз",
|
"registerHeading": "Тіркеліңіз",
|
||||||
"registerIntro": "Атыңыз бен құпиясөзді таңдаңыз және өзіңіз туралы деректерді толтырыңыз. Тіркелген соң бір күндік мәзір мен жаттығу жоспарын аша аласыз.",
|
"registerIntro": "Атыңыз бен құпиясөзді таңдаңыз, содан кейін тамақтануды есептеу үшін деректеріңізді толтырыңыз. Тіркелгеннен кейін профиліңіз ашылады.",
|
||||||
"toRegister": "Алғаш рет келдіңіз бе? Тіркелу",
|
"toRegister": "Алғаш рет келдіңіз бе? Тіркелу",
|
||||||
"toLogin": "Тіркелгенсіз бе? Кіру",
|
"toLogin": "Тіркелгенсіз бе? Кіру",
|
||||||
"sexChoose": "Жынысыңызды таңдаңыз",
|
"sexChoose": "Жынысыңызды таңдаңыз",
|
||||||
@ -192,12 +188,11 @@
|
|||||||
"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": "Open your daily menu or workout plan. To recalculate portions, change your details or goal and save.",
|
"next": "Edit and save your details to update the estimate and portions below.",
|
||||||
"norm": "Daily estimate",
|
"norm": "Daily estimate",
|
||||||
"calories": "kcal",
|
"calories": "kcal",
|
||||||
"protein": "g protein",
|
"protein": "g protein",
|
||||||
"menu": "Example daily menu",
|
"menu": "Example daily menu",
|
||||||
"menuOpen": "Open daily menu",
|
|
||||||
"menuHint": "Portions follow your calorie estimate. Ingredients and nutrition are approximate; check for allergens.",
|
"menuHint": "Portions follow your calorie estimate. Ingredients and nutrition are approximate; check for allergens.",
|
||||||
"breakfast": "Breakfast: oatmeal with yogurt",
|
"breakfast": "Breakfast: oatmeal with yogurt",
|
||||||
"lunch": "Lunch: chicken with rice and vegetables",
|
"lunch": "Lunch: chicken with rice and vegetables",
|
||||||
@ -209,7 +204,6 @@
|
|||||||
"passwordHint": "12–128 characters. A long password helps protect your profile.",
|
"passwordHint": "12–128 characters. A long password helps protect your profile.",
|
||||||
"loading": "Loading…",
|
"loading": "Loading…",
|
||||||
"errors": {
|
"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.",
|
"height": "Height is invalid. Enter a number from 100 to 250 cm.",
|
||||||
"weight": "Weight is invalid. Enter a number from 25 to 350 kg.",
|
"weight": "Weight is invalid. Enter a number from 25 to 350 kg.",
|
||||||
"age": "Age is invalid. Enter a whole number from 18 to 100.",
|
"age": "Age is invalid. Enter a whole number from 18 to 100.",
|
||||||
@ -235,7 +229,7 @@
|
|||||||
"loginHeading": "Sign in to your profile",
|
"loginHeading": "Sign in to your profile",
|
||||||
"loginIntro": "Enter your username and password. Your saved details and nutrition estimate will open after you sign in.",
|
"loginIntro": "Enter your username and password. Your saved details and nutrition estimate will open after you sign in.",
|
||||||
"registerHeading": "Create your account",
|
"registerHeading": "Create your account",
|
||||||
"registerIntro": "Choose a username and password and enter your details. After signing up, you can open your daily menu and workout plan.",
|
"registerIntro": "Choose a username and password, then enter your details for a nutrition estimate. Your profile will open after registration.",
|
||||||
"toRegister": "New here? Create account",
|
"toRegister": "New here? Create account",
|
||||||
"toLogin": "Already have an account? Sign in",
|
"toLogin": "Already have an account? Sign in",
|
||||||
"sexChoose": "Select your sex",
|
"sexChoose": "Select your sex",
|
||||||
|
|||||||
@ -5,8 +5,7 @@ const scrypt = promisify(derive);
|
|||||||
export class InputError extends Error {
|
export class InputError extends Error {
|
||||||
constructor(key, status = 400) { super(key); this.status = status; }
|
constructor(key, status = 400) { super(key); this.status = status; }
|
||||||
}
|
}
|
||||||
const goalFactors = {lose: 0.85, maintain: 1, gain: 1.1};
|
export function validateProfile(input) {
|
||||||
export function validateProfile(input, defaultGoal = 'maintain') {
|
|
||||||
const out = {};
|
const out = {};
|
||||||
for (const [key, min, max] of [['height',100,250],['weight',25,350],['age',18,100]]) {
|
for (const [key, min, max] of [['height',100,250],['weight',25,350],['age',18,100]]) {
|
||||||
const value = input[key];
|
const value = input[key];
|
||||||
@ -19,14 +18,11 @@ export function validateProfile(input, defaultGoal = 'maintain') {
|
|||||||
out.sex = input.sex;
|
out.sex = input.sex;
|
||||||
if (!['1.2','1.375','1.55','1.725'].includes(String(input.activity))) throw new InputError('activity');
|
if (!['1.2','1.375','1.55','1.725'].includes(String(input.activity))) throw new InputError('activity');
|
||||||
out.activity = Number(input.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;
|
return out;
|
||||||
}
|
}
|
||||||
export function nutrition(profile) {
|
export function nutrition(profile) {
|
||||||
const p = validateProfile(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 calories = Math.round((10*p.weight + 6.25*p.height - 5*p.age + (p.sex === 'male' ? 5 : -161))*p.activity);
|
||||||
const protein = Math.round(p.weight*1.6);
|
const protein = Math.round(p.weight*1.6);
|
||||||
// One illustrative day: proportions sum to the daily energy estimate.
|
// One illustrative day: proportions sum to the daily energy estimate.
|
||||||
const menu = [
|
const menu = [
|
||||||
@ -76,11 +72,11 @@ export class ProfileService {
|
|||||||
return user;
|
return user;
|
||||||
}
|
}
|
||||||
read(token) {
|
read(token) {
|
||||||
const user = this.user(token), profile = validateProfile(JSON.parse(user.profile));
|
const user = this.user(token), profile = JSON.parse(user.profile);
|
||||||
return {username:user.username,profile,nutrition:nutrition(profile)};
|
return {username:user.username,profile,nutrition:nutrition(profile)};
|
||||||
}
|
}
|
||||||
update(token,input) {
|
update(token,input) {
|
||||||
const user = this.user(token), profile = validateProfile(input,JSON.parse(user.profile).goal);
|
const user = this.user(token), profile = validateProfile(input);
|
||||||
this.db.prepare('UPDATE users SET profile=? WHERE id=?').run(JSON.stringify(profile),user.id);
|
this.db.prepare('UPDATE users SET profile=? WHERE id=?').run(JSON.stringify(profile),user.id);
|
||||||
return this.read(token);
|
return this.read(token);
|
||||||
}
|
}
|
||||||
|
|||||||
2
sw.js
2
sw.js
@ -1,5 +1,5 @@
|
|||||||
// Сервис-воркер: приложение открывается без интернета (сначала сеть, при отсутствии — копия из кэша).
|
// Сервис-воркер: приложение открывается без интернета (сначала сеть, при отсутствии — копия из кэша).
|
||||||
const CACHE = 'tpt-v27-clear-goal';
|
const CACHE = 'tpt-v28-norms-hint';
|
||||||
const FILES = ['./', 'index.html', 'gym-plan.i18n.js', 'manifest.webmanifest', 'icon.svg', 'recipes.html', 'recipes.css', 'recipes.js', 'recipes-core.js', 'recipes-status.i18n.js', 'recipes.data.json', 'recipes.i18n.json', 'telemetry.js', 'assets/oats.jpg', 'assets/chicken.jpg', 'assets/salad.jpg'];
|
const FILES = ['./', 'index.html', 'gym-plan.i18n.js', 'manifest.webmanifest', 'icon.svg', 'recipes.html', 'recipes.css', 'recipes.js', 'recipes-core.js', 'recipes-status.i18n.js', 'recipes.data.json', 'recipes.i18n.json', 'telemetry.js', 'assets/oats.jpg', 'assets/chicken.jpg', 'assets/salad.jpg'];
|
||||||
self.addEventListener('install', e => { e.waitUntil(caches.open(CACHE).then(c => c.addAll(FILES)).then(() => self.skipWaiting())); });
|
self.addEventListener('install', e => { e.waitUntil(caches.open(CACHE).then(c => c.addAll(FILES)).then(() => self.skipWaiting())); });
|
||||||
self.addEventListener('activate', e => {
|
self.addEventListener('activate', e => {
|
||||||
|
|||||||
@ -1,54 +0,0 @@
|
|||||||
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');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -1,47 +0,0 @@
|
|||||||
const { randomUUID } = require('node:crypto');
|
|
||||||
const { test, expect } = require('@playwright/test');
|
|
||||||
|
|
||||||
test.use({ viewport: { width: 375, height: 740 }, locale: 'ru-RU' });
|
|
||||||
|
|
||||||
test('Готовое блюдо и занятие из плана сохраняются в дневнике', async ({ page }) => {
|
|
||||||
await page.goto('/?lang=ru');
|
|
||||||
await page.locator('[data-welcome-next]').click();
|
|
||||||
await page.locator('#field-username').fill('menu' + randomUUID().slice(0, 8));
|
|
||||||
await page.locator('#field-password').fill('menu-workout-test-123');
|
|
||||||
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 page.locator('button[type=submit]').click();
|
|
||||||
await page.locator('a[href="/tracker?lang=ru"]').click();
|
|
||||||
await expect(page).toHaveURL(/\/tracker\?lang=ru$/);
|
|
||||||
|
|
||||||
const suggestion = page.locator('.dish').filter({
|
|
||||||
has: page.getByRole('button', { name: 'Выбрать', exact: true })
|
|
||||||
});
|
|
||||||
await expect(suggestion.locator('[data-ingredients] li').first()).toBeVisible();
|
|
||||||
const dishName = await suggestion.locator('.main b').innerText();
|
|
||||||
await suggestion.getByRole('button', { name: 'Выбрать', exact: true }).click();
|
|
||||||
const selectedDish = page.locator('.dish').filter({ hasText: dishName });
|
|
||||||
await expect(selectedDish.getByRole('button', { name: 'Убрать рецепт из дня' })).toBeVisible();
|
|
||||||
|
|
||||||
await page.locator('[data-plan-open]').click();
|
|
||||||
const planDays = page.locator('#view section');
|
|
||||||
await expect(planDays).toHaveCount(4);
|
|
||||||
const firstDay = planDays.first();
|
|
||||||
await expect(firstDay).toContainText('День 1 — верх тела');
|
|
||||||
await firstDay.getByRole('button', { name: 'Записать тренировку' }).click();
|
|
||||||
const workout = page.locator('.sheet');
|
|
||||||
await expect(workout.getByLabel('Длительность, мин')).toHaveValue('120');
|
|
||||||
await expect(workout.getByPlaceholder('Название упражнения').first()).toHaveValue('Жим гантелей лёжа');
|
|
||||||
await workout.getByRole('button', { name: 'Сохранить', exact: true }).click();
|
|
||||||
await expect(workout).toHaveCount(0);
|
|
||||||
|
|
||||||
await page.reload();
|
|
||||||
await expect(selectedDish).toBeVisible();
|
|
||||||
await page.locator('#tabs').getByRole('button', { name: /Тренировки/ }).click();
|
|
||||||
const savedWorkout = page.locator('#view .item').filter({ hasText: 'Жим гантелей лёжа' });
|
|
||||||
await expect(savedWorkout).toContainText('Силовая');
|
|
||||||
await expect(savedWorkout).toContainText('120 мин');
|
|
||||||
});
|
|
||||||
@ -1,17 +0,0 @@
|
|||||||
const { test, expect } = require('@playwright/test');
|
|
||||||
const translations = require('../../profile/i18n.json');
|
|
||||||
test.beforeEach(async ({ page }) => { await page.addInitScript(() => sessionStorage.setItem('tpt.welcomeSeen','1')); });
|
|
||||||
test.use({ viewport: { width: 360, height: 640 } });
|
|
||||||
for (const lang of ['ru', 'kk', 'en']) {
|
|
||||||
test(`Регистрация: подсказка пола и возврат ко входу (${lang})`, async ({ page }) => {
|
|
||||||
const t = translations[lang];
|
|
||||||
await page.goto('/?lang=' + lang);
|
|
||||||
await page.getByRole('button', { name: t.toRegister, exact: true }).click();
|
|
||||||
await expect(page.locator('#field-sex option').first()).toHaveText(t.sexChoose);
|
|
||||||
await expect(page.locator('#field-sex')).not.toContainText('Choose');
|
|
||||||
await expect(page.locator('#field-sex-hint')).toHaveText(t.sexHint);
|
|
||||||
await page.getByRole('button', { name: t.toLogin, exact: true }).click();
|
|
||||||
await expect(page.getByRole('heading', { name: t.loginHeading })).toBeVisible();
|
|
||||||
await expect(page.locator('#field-sex')).toHaveCount(0);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -25,10 +25,7 @@ const nutrition = card => [...card.querySelectorAll('[data-nutrition] .dish-row'
|
|||||||
|
|
||||||
test('Сценарий: карточка блюда показывает фото, граммы, КБЖУ и шаги', t => {
|
test('Сценарий: карточка блюда показывает фото, граммы, КБЖУ и шаги', t => {
|
||||||
const { dom, document } = open(); t.after(() => dom.window.close());
|
const { dom, document } = open(); t.after(() => dom.window.close());
|
||||||
document.querySelector('[data-add-recipe]').click();
|
const card = [...document.querySelectorAll('.item')].find(i => i.querySelector('[data-nutrition]'));
|
||||||
const card = [...document.querySelectorAll('.sheet .dish')].find(dish =>
|
|
||||||
dish.querySelector('.main b').textContent === 'Овсянка с ягодами'
|
|
||||||
);
|
|
||||||
assert.ok(card, 'нет карточки с КБЖУ');
|
assert.ok(card, 'нет карточки с КБЖУ');
|
||||||
assert.ok(card.querySelector('img'));
|
assert.ok(card.querySelector('img'));
|
||||||
assert.match(nutrition(card), /Порция \d+ г · \d+ ккал · Б .* · Ж .* · У /);
|
assert.match(nutrition(card), /Порция \d+ г · \d+ ккал · Б .* · Ж .* · У /);
|
||||||
@ -149,10 +146,7 @@ test('Сценарий: Длинный состав на узком экране
|
|||||||
|
|
||||||
test('Сценарий: рецепт по шагам раскрывается и закрывается кнопкой', t => {
|
test('Сценарий: рецепт по шагам раскрывается и закрывается кнопкой', t => {
|
||||||
const { dom, document } = open(); t.after(() => dom.window.close());
|
const { dom, document } = open(); t.after(() => dom.window.close());
|
||||||
document.querySelector('[data-add-recipe]').click();
|
const card = [...document.querySelectorAll('.item')].find(i => i.querySelector('[data-nutrition]'));
|
||||||
const card = [...document.querySelectorAll('.sheet .dish')].find(dish =>
|
|
||||||
dish.querySelector('.main b').textContent === 'Овсянка с ягодами'
|
|
||||||
);
|
|
||||||
const btn = card.querySelector('[data-recipe-toggle]');
|
const btn = card.querySelector('[data-recipe-toggle]');
|
||||||
const list = card.querySelector('[data-steps]');
|
const list = card.querySelector('[data-steps]');
|
||||||
assert.equal(btn.textContent, 'Показать рецепт');
|
assert.equal(btn.textContent, 'Показать рецепт');
|
||||||
|
|||||||
@ -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],goal:['',null,'unknown']})) {
|
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 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,19 +69,3 @@ 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