Compare commits
7 Commits
492c2eb5f6
...
e5d9af0c64
| Author | SHA1 | Date | |
|---|---|---|---|
| e5d9af0c64 | |||
| 9e7b1beead | |||
| fc62abb93a | |||
| 66c6230490 | |||
| 50e8708f97 | |||
| 3c0502db69 | |||
| 333bb59268 |
@ -14,3 +14,7 @@ deploy
|
|||||||
*.md
|
*.md
|
||||||
Dockerfile
|
Dockerfile
|
||||||
.dockerignore
|
.dockerignore
|
||||||
|
|
||||||
|
generated
|
||||||
|
test-results
|
||||||
|
playwright-report
|
||||||
|
|||||||
@ -9,7 +9,7 @@ check="$1"
|
|||||||
cfg=.peppa/project.json
|
cfg=.peppa/project.json
|
||||||
cmd=$(jq -r --arg c "$check" '.checks[$c] // empty' "$cfg" 2>/dev/null)
|
cmd=$(jq -r --arg c "$check" '.checks[$c] // empty' "$cfg" 2>/dev/null)
|
||||||
if [[ -z "$cmd" ]]; then
|
if [[ -z "$cmd" ]]; then
|
||||||
echo "peppa: проверка «$check» не настроена — пропуск"
|
echo "peppa: проверка «${check}» не настроена — пропуск"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
log=$(mktemp)
|
log=$(mktemp)
|
||||||
|
|||||||
@ -69,8 +69,9 @@ report() { # report <status> [reason]
|
|||||||
}
|
}
|
||||||
|
|
||||||
dc() { # dc <image> <compose args…>
|
dc() { # dc <image> <compose args…>
|
||||||
local img="$1"; shift
|
local img="$1" sentry_env=staging; shift
|
||||||
IMAGE="$img" HOST="$host" ROUTER="$router" APP_PORT="$port" docker compose -p "$project" -f "$compose" "$@"
|
[[ $env_name == prod ]] && sentry_env=prod
|
||||||
|
SENTRY_RELEASE="$sha" SENTRY_ENVIRONMENT="${SENTRY_ENVIRONMENT:-$sentry_env}" IMAGE="$img" HOST="$host" ROUTER="$router" APP_PORT="$port" docker compose -p "$project" -f "$compose" "$@"
|
||||||
}
|
}
|
||||||
|
|
||||||
healthy() {
|
healthy() {
|
||||||
|
|||||||
5
.gitignore
vendored
5
.gitignore
vendored
@ -2,3 +2,8 @@ node_modules/
|
|||||||
.env
|
.env
|
||||||
.env.local
|
.env.local
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
node_modules/
|
||||||
|
test-results/
|
||||||
|
playwright-report/
|
||||||
|
generated/
|
||||||
|
|||||||
@ -14,5 +14,8 @@
|
|||||||
- TPTIP-10: готовые блюда (BUILTIN_RECIPES в index.html) хранят КБЖУ на порцию, grams и steps; «Выбрать» (chooseRecipe) ставит блюдо на день и пишет meals-запись; тест tests/dish-card.test.js.
|
- TPTIP-10: готовые блюда (BUILTIN_RECIPES в index.html) хранят КБЖУ на порцию, grams и steps; «Выбрать» (chooseRecipe) ставит блюдо на день и пишет meals-запись; тест tests/dish-card.test.js.
|
||||||
|
|
||||||
- TPTIP-11: страницы-заглушки about нет (удалена); мастер (startWizard) показывает пустые поля с подсказками, defaultData с 30/175/75 не менять — на нём держатся тесты.
|
- TPTIP-11: страницы-заглушки about нет (удалена); мастер (startWizard) показывает пустые поля с подсказками, defaultData с 30/175/75 не менять — на нём держатся тесты.
|
||||||
|
- TPTIP-14: подсказки диапазонов в мастере — hint в numField (calcFields); подписи колец в ring(...) 'г белка'/'мл воды'; кнопку «Далее» не переименовывать (тесты ищут по тексту).
|
||||||
## Грабли
|
## Грабли
|
||||||
- На 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-3: каталог /recipes.html (ru/kk/en), локальные фото assets; npm run build перед npm start; браузер npx playwright test. Сохранить маршруты recipes и сборку telemetry при объединении server.js/Dockerfile.
|
||||||
|
|||||||
@ -6,7 +6,8 @@
|
|||||||
"checks": {
|
"checks": {
|
||||||
"install": "npm ci",
|
"install": "npm ci",
|
||||||
"lint": "npm run lint",
|
"lint": "npm run lint",
|
||||||
"test": "npm test"
|
"test": "npm test",
|
||||||
|
"build": "npm run build"
|
||||||
},
|
},
|
||||||
"deploy": {
|
"deploy": {
|
||||||
"compose": "deploy/compose.yml",
|
"compose": "deploy/compose.yml",
|
||||||
|
|||||||
12
Dockerfile
12
Dockerfile
@ -1,8 +1,16 @@
|
|||||||
# Образ стенда (TPTIP-6): статическое приложение + мини-сервер server.js (/healthz, $PORT).
|
FROM node:22-bookworm-slim AS build
|
||||||
# COPY . . с .dockerignore — набор файлов приложения меняется от задачи к задаче, а сервер отдаёт только белый список.
|
WORKDIR /app
|
||||||
|
COPY package.json package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY telemetry-client.js ./
|
||||||
|
RUN npm run build
|
||||||
|
RUN npm prune --omit=dev
|
||||||
|
|
||||||
FROM node:22-bookworm-slim
|
FROM node:22-bookworm-slim
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production PORT=3000
|
ENV NODE_ENV=production PORT=3000
|
||||||
|
COPY --from=build /app/node_modules ./node_modules
|
||||||
|
COPY --from=build /app/generated ./generated
|
||||||
COPY . .
|
COPY . .
|
||||||
EXPOSE 3000
|
EXPOSE 3000
|
||||||
USER node
|
USER node
|
||||||
|
|||||||
9
assets/README.md
Normal file
9
assets/README.md
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
# Фотографии
|
||||||
|
|
||||||
|
Unsplash, локальные копии для иллюстрации блюд; оригинальный вид приготовления может отличаться.
|
||||||
|
|
||||||
|
oats: https://images.unsplash.com/photo-1517673400267-0251440c45dc?auto=format&fit=crop&w=900&q=80
|
||||||
|
chicken: https://images.unsplash.com/photo-1532550907401-a500c9a57435?auto=format&fit=crop&w=900&q=80
|
||||||
|
salad: https://images.unsplash.com/photo-1512621776951-a57141f2eefd?auto=format&fit=crop&w=900&q=80
|
||||||
|
|
||||||
|
Лицензия: https://unsplash.com/license
|
||||||
BIN
assets/chicken.jpg
Normal file
BIN
assets/chicken.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 130 KiB |
BIN
assets/oats.jpg
Normal file
BIN
assets/oats.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 108 KiB |
BIN
assets/salad.jpg
Normal file
BIN
assets/salad.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 139 KiB |
@ -7,6 +7,10 @@ services:
|
|||||||
image: ${IMAGE}
|
image: ${IMAGE}
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
environment:
|
environment:
|
||||||
|
SENTRY_DSN: "${SENTRY_DSN:-}"
|
||||||
|
PUBLIC_SENTRY_DSN: "${PUBLIC_SENTRY_DSN:-}"
|
||||||
|
SENTRY_RELEASE: "${SENTRY_RELEASE:-}"
|
||||||
|
SENTRY_ENVIRONMENT: "${SENTRY_ENVIRONMENT:-dev}"
|
||||||
PORT: "${APP_PORT:-3000}"
|
PORT: "${APP_PORT:-3000}"
|
||||||
networks:
|
networks:
|
||||||
- traefik_default
|
- traefik_default
|
||||||
|
|||||||
@ -36,3 +36,7 @@
|
|||||||
| Готовые занятия в зале | план тренировок | программа жиросжигания | Четыре общих занятия без персонализации |
|
| Готовые занятия в зале | план тренировок | программа жиросжигания | Четыре общих занятия без персонализации |
|
||||||
| Объём упражнения | подходы, повторы | сеты, репы | Количество повторений упражнения |
|
| Объём упражнения | подходы, повторы | сеты, репы | Количество повторений упражнения |
|
||||||
| Сохранённые занятия | журнал тренировок | лог тренировок | Общий список занятий пользователя |
|
| Сохранённые занятия | журнал тренировок | лог тренировок | Общий список занятий пользователя |
|
||||||
|
| Каталог блюд | рецепты | — | Фото, состав и приготовление блюда |
|
||||||
|
| Пищевая ценность | калории, белки, жиры, углеводы | — | Приблизительное значение на порцию |
|
||||||
|
| Количество еды | порции | — | Количество порций одного блюда |
|
||||||
|
| Состав блюда | ингредиенты | — | Продукты с массой до приготовления |
|
||||||
|
|||||||
25
docs/recipes.md
Normal file
25
docs/recipes.md
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# Каталог рецептов
|
||||||
|
|
||||||
|
Откройте `/recipes.html`, язык: `?lang=ru`, `?lang=kk` или `?lang=en`.
|
||||||
|
Каталог открывается из карточки рецептов на главной. Корень `/` сохраняет существующий трекер.
|
||||||
|
|
||||||
|
Запуск: `npm ci`, `npm start`. Проверки: `npm run lint`, `npm test`.
|
||||||
|
Проверка браузера: `npx playwright install chromium`, затем `npx playwright test`.
|
||||||
|
|
||||||
|
Фотографии лежат в assets, источники — assets/README.md. Они иллюстративные.
|
||||||
|
КБЖУ рассчитывается по приблизительным значениям ингредиентов на 100 г
|
||||||
|
в recipes.data.json; массы сырые, указанная вода добавляется к блюду.
|
||||||
|
Показатели зависят от производителя продуктов. Количество порций — 1–8.
|
||||||
|
Пользовательские тексты — recipes.i18n.json и recipes-status.i18n.js.
|
||||||
|
При изменении сообщения загрузки/ошибки обновляйте оба файла.
|
||||||
|
|
||||||
|
Проверенные видимые тексты: заголовок, вступление, выбор языка, названия блюд,
|
||||||
|
время, порции и подписи кнопок, КБЖУ, ингредиенты, граммы, шаги приготовления,
|
||||||
|
пояснение о сыром весе и приблизительных значениях, сообщение отсутствия фото,
|
||||||
|
ошибка загрузки и повторная попытка, подвал. Сверены с docs/glossary.md;
|
||||||
|
обращение на «вы», технические идентификаторы и суммы отсутствуют.
|
||||||
|
|
||||||
|
Мониторинг ошибок: `SENTRY_DSN` для сервера, `PUBLIC_SENTRY_DSN` для браузера,
|
||||||
|
`SENTRY_RELEASE` — SHA версии, `SENTRY_ENVIRONMENT` — dev/staging/prod.
|
||||||
|
Без DSN SDK не инициализируется, sendDefaultPii выключен. Клиентский SDK
|
||||||
|
собирается через `npm run build`; перед npm start выполните эту команду.
|
||||||
@ -1,6 +1,7 @@
|
|||||||
import js from '@eslint/js';
|
import js from '@eslint/js';
|
||||||
import globals from 'globals';
|
import globals from 'globals';
|
||||||
export default [
|
export default [
|
||||||
|
{ ignores: ['node_modules/**', 'generated/**', 'test-results/**'] },
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
{ files: ['**/*.{js,mjs}'], languageOptions: { globals: { ...globals.browser, ...globals.node, ...globals.serviceworker } } }
|
{ files: ['**/*.{js,mjs}'], languageOptions: { globals: { ...globals.browser, ...globals.node, ...globals.serviceworker } } }
|
||||||
];
|
];
|
||||||
|
|||||||
14
index.html
14
index.html
@ -125,6 +125,7 @@ input:focus,select:focus,textarea:focus,button:focus-visible{outline:2px solid v
|
|||||||
<div id="toast" role="status"></div>
|
<div id="toast" role="status"></div>
|
||||||
|
|
||||||
<script src="gym-plan.i18n.js"></script>
|
<script src="gym-plan.i18n.js"></script>
|
||||||
|
<script src="recipes-status.i18n.js"></script>
|
||||||
<script>
|
<script>
|
||||||
/* =====================================================================
|
/* =====================================================================
|
||||||
СЛОЙ ДАННЫХ (чистые функции, без DOM) — проверяется tests/logic.test.js
|
СЛОЙ ДАННЫХ (чистые функции, без DOM) — проверяется tests/logic.test.js
|
||||||
@ -667,8 +668,8 @@ function viewToday() {
|
|||||||
return h('div', null, dateNav(),
|
return h('div', null, dateNav(),
|
||||||
h('div', { class: 'card' },
|
h('div', { class: 'card' },
|
||||||
h('div', { class: 'rings' },
|
h('div', { class: 'rings' },
|
||||||
ring('Калории', t.kcal, s.kcal, 'ккал', 'var(--kcal)'), ring('Белки', t.protein, s.protein, 'г', 'var(--prot)'),
|
ring('Калории', t.kcal, s.kcal, 'ккал', 'var(--kcal)'), ring('Белки', t.protein, s.protein, 'г белка', 'var(--prot)'),
|
||||||
ring('Жиры', t.fat, s.fat, 'г', 'var(--fat)'), ring('Углеводы', t.carbs, s.carbs, 'г', 'var(--carb)'), ring('Вода', t.water, s.water, 'мл', 'var(--water)')),
|
ring('Жиры', t.fat, s.fat, 'г жиров', 'var(--fat)'), ring('Углеводы', t.carbs, s.carbs, 'г углеводов', 'var(--carb)'), ring('Вода', t.water, s.water, 'мл воды', 'var(--water)')),
|
||||||
h('div', { class: 'row', style: 'justify-content:center;margin-top:10px' },
|
h('div', { class: 'row', style: 'justify-content:center;margin-top:10px' },
|
||||||
t.water > 0 ? h('button', { class: 'chip minus', 'aria-label': 'Убрать 250 мл воды', onclick: removeLastWater }, '−250') : null,
|
t.water > 0 ? h('button', { class: 'chip minus', 'aria-label': 'Убрать 250 мл воды', onclick: removeLastWater }, '−250') : null,
|
||||||
h('button', { class: 'chip on', onclick: () => addWater(250) }, '+250 мл воды')),
|
h('button', { class: 'chip on', onclick: () => addWater(250) }, '+250 мл воды')),
|
||||||
@ -900,6 +901,7 @@ function recipesCard() {
|
|||||||
return h('div', { class: 'card' },
|
return h('div', { class: 'card' },
|
||||||
h('div', { class: 'row between' }, h('h3', null, 'Рецепты на день'),
|
h('div', { class: 'row between' }, h('h3', null, 'Рецепты на день'),
|
||||||
h('button', { onclick: openRecipePicker }, '+ Рецепт')),
|
h('button', { onclick: openRecipePicker }, '+ Рецепт')),
|
||||||
|
globalThis.RecipeMessages ? h('a', { href: '/recipes.html?lang=ru' }, globalThis.RecipeMessages.ru.title) : null,
|
||||||
planned.length ? planned.map(({ p, r }) => recipeView(r, h('button', { class: 'ghost icon', 'aria-label': 'Убрать рецепт из дня', onclick: () => { db.plan = db.plan.filter(x => x.id !== p.id); save(); render(); } }, '✕')))
|
planned.length ? planned.map(({ p, r }) => recipeView(r, h('button', { class: 'ghost icon', 'aria-label': 'Убрать рецепт из дня', onclick: () => { db.plan = db.plan.filter(x => x.id !== p.id); save(); render(); } }, '✕')))
|
||||||
: suggestionBlock());
|
: suggestionBlock());
|
||||||
}
|
}
|
||||||
@ -1135,9 +1137,9 @@ function viewStats() {
|
|||||||
function calcFields(pr, hints) {
|
function calcFields(pr, hints) {
|
||||||
hints = hints || {};
|
hints = hints || {};
|
||||||
const sex = selectField('Пол', [['m', 'Мужской'], ['f', 'Женский']], pr.sex);
|
const sex = selectField('Пол', [['m', 'Мужской'], ['f', 'Женский']], pr.sex);
|
||||||
const age = numField('Возраст, лет', { value: pr.age, placeholder: hints.age, required: true, int: true, min: 10, max: 100 });
|
const age = numField('Возраст, лет', { value: pr.age, placeholder: hints.age, required: true, int: true, min: 10, max: 100, hint: 'От 10 до 100 лет' });
|
||||||
const height = numField('Рост, см', { value: pr.height, placeholder: hints.height, required: true, min: 100, max: 250 });
|
const height = numField('Рост, см', { value: pr.height, placeholder: hints.height, required: true, min: 100, max: 250, hint: 'От 100 до 250 см' });
|
||||||
const weight = numField('Вес, кг', { value: pr.weight, placeholder: hints.weight, required: true, min: 25, max: 400 });
|
const weight = numField('Вес, кг', { value: pr.weight, placeholder: hints.weight, required: true, min: 25, max: 400, hint: 'От 25 до 400 кг' });
|
||||||
const act = selectField('Активность', ACTIVITY, pr.activity);
|
const act = selectField('Активность', ACTIVITY, pr.activity);
|
||||||
return {
|
return {
|
||||||
el: h('div', null, h('div', { class: 'grid2' }, sex, age), h('div', { class: 'grid2' }, height, weight), act),
|
el: h('div', null, h('div', { class: 'grid2' }, sex, age), h('div', { class: 'grid2' }, height, weight), act),
|
||||||
@ -1264,7 +1266,7 @@ function startWizard() {
|
|||||||
const body = h('div');
|
const body = h('div');
|
||||||
let close;
|
let close;
|
||||||
const step1 = () => body.replaceChildren(
|
const step1 = () => body.replaceChildren(
|
||||||
h('p', { class: 'muted' }, 'Шаг 1 из 2. Выберите цель и укажите данные — мы посчитаем дневные нормы.'),
|
h('p', { class: 'muted' }, 'Шаг 1 из 2. Выберите цель и укажите данные. На втором шаге вы увидите свои дневные нормы и сможете их поправить.'),
|
||||||
goalChips(() => goal, k => { goal = k; }), h('div', { style: 'height:8px' }), calc.el,
|
goalChips(() => goal, k => { goal = k; }), h('div', { style: 'height:8px' }), calc.el,
|
||||||
h('div', { class: 'foot' }, h('button', { class: 'primary', onclick: () => { const p = calc.read(); if (!p) return; db.settings.goal = goal; db.settings.profile = p; step2(p); } }, 'Далее')));
|
h('div', { class: 'foot' }, h('button', { class: 'primary', onclick: () => { const p = calc.read(); if (!p) return; db.settings.goal = goal; db.settings.profile = p; step2(p); } }, 'Далее')));
|
||||||
const step2 = p => {
|
const step2 = p => {
|
||||||
|
|||||||
@ -0,0 +1,2 @@
|
|||||||
|
## Решения
|
||||||
|
- Только тексты и подсказки в index.html (numField hint); логика мастера не менялась, кнопка «Далее» осталась прежней.
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
## Why
|
||||||
|
Мастер первого входа должен быть понятным: что будет на шаге 2, какие значения допустимы, и единицы в кольцах должны читаться без догадок.
|
||||||
|
## What Changes
|
||||||
|
- Шаг 1 говорит, что на шаге 2 будут дневные нормы, которые можно поправить.
|
||||||
|
- Под полями возраста, роста и веса — допустимые значения.
|
||||||
|
- Подписи колец: «ккал», «г белка», «г жиров», «г углеводов», «мл воды».
|
||||||
@ -0,0 +1,16 @@
|
|||||||
|
## ADDED Requirements
|
||||||
|
|
||||||
|
### Requirement: Мастер объясняет шаги и допустимые значения
|
||||||
|
Шаг 1 SHALL сообщать, что будет на шаге 2; поля возраста, роста и веса SHALL иметь подсказку допустимого диапазона; кольца SHALL подписывать единицы полностью.
|
||||||
|
|
||||||
|
#### Scenario: Первый шаг
|
||||||
|
- **GIVEN** мастер открыт впервые
|
||||||
|
- **WHEN** пользователь смотрит на шаг 1
|
||||||
|
- **THEN** видно «На втором шаге вы увидите свои дневные нормы»
|
||||||
|
- **AND** под полями «От 10 до 100 лет», «От 100 до 250 см», «От 25 до 400 кг»
|
||||||
|
|
||||||
|
#### Scenario: Завершение мастера
|
||||||
|
- **GIVEN** пользователь ввёл 40 лет, 170 см, 65 кг и дошёл до шага 2
|
||||||
|
- **WHEN** он нажимает «Готово»
|
||||||
|
- **THEN** окно закрывается
|
||||||
|
- **AND** кольца показывают «ккал», «г белка», «г жиров», «г углеводов», «мл воды»
|
||||||
@ -0,0 +1,3 @@
|
|||||||
|
- [x] Анонс второго шага и подсказки диапазонов
|
||||||
|
- [x] Полные единицы в кольцах
|
||||||
|
- [x] Тесты в tests/wizard.test.js
|
||||||
@ -12,4 +12,7 @@
|
|||||||
- Node tests и ESLint; команды записываются в checks, для preview требуется Dockerfile и deploy из шаблона Node.
|
- Node tests и ESLint; команды записываются в checks, для preview требуется Dockerfile и deploy из шаблона Node.
|
||||||
|
|
||||||
## Risks / Trade-offs
|
## Risks / Trade-offs
|
||||||
Фото иллюстрируют блюдо и могут отличаться от результата → подпись на странице. Погрешность состава → явная подпись «примерно». Личные загрузки и Sentry не добавляются: нет нового backend поведения, отдельная инфраструктура вне задачи.
|
Фото иллюстрируют блюдо и могут отличаться от результата → подпись на странице. Погрешность состава → явная подпись «примерно». Личные загрузки вне задачи. Sentry подключён по общему правилу проекта: DSN только из env, без DSN SDK не запускается; sendDefaultPii=false, release и environment из переменных окружения. Клиентский пакет собирается esbuild локально, внешнего CDN нет.
|
||||||
|
|
||||||
|
## Интеграция после обновления main
|
||||||
|
TPTIP-5 вошла в main во время проверки. При rebase сохранены index.html, gym-plan, прежние тесты сервера, fallback about.html, ESLint 10 и jsdom. Добавлены ссылка из карточки рецептов, маршруты каталога и ресурсы service worker, версия кэша повышена. Docker сохраняет COPY . . с исключениями и USER node, дополняя сборкой SDK.
|
||||||
@ -1,12 +1,12 @@
|
|||||||
# Tasks
|
# Tasks
|
||||||
|
|
||||||
## 1. Каталог
|
## 1. Каталог
|
||||||
- [ ] 1.1 Добавить три рецепта, переводы ru/kk/en и локальные фотографии; проверить полноту данных и пересчёт тестами, записать источники фото.
|
- [x] 1.1 Добавить три рецепта, переводы ru/kk/en и локальные фотографии; проверить полноту данных и пересчёт тестами, записать источники фото.
|
||||||
- [ ] 1.2 Сделать адаптивную страницу, управление порциями и замену недоступного фото; проверить в браузере, сверить тексты со словарём.
|
- [x] 1.2 Сделать адаптивную страницу, управление порциями и замену недоступного фото; проверить в браузере, сверить тексты со словарём.
|
||||||
|
|
||||||
## 2. Доставка и проверка
|
## 2. Доставка и проверка
|
||||||
- [ ] 2.1 Подключить выдачу страницы и ресурсов, настроить линтер и проверки; проверить HTTP-маршруты и запрет произвольных файлов тестами.
|
- [x] 2.1 Подключить выдачу страницы и ресурсов, настроить линтер и проверки; проверить HTTP-маршруты и запрет произвольных файлов тестами.
|
||||||
- [ ] 2.2 Запустить проверки проекта, проверить страницу на узком экране и выполнить openspec validate.
|
- [x] 2.2 Запустить проверки проекта, проверить страницу на узком экране и выполнить openspec validate.
|
||||||
|
|
||||||
## Workflow follow-up
|
## Workflow follow-up
|
||||||
- Записать память, архивировать change, открыть PR и передать на ревью.
|
- Записать память, архивировать change, открыть PR и передать на ревью.
|
||||||
@ -1,7 +1,7 @@
|
|||||||
# recipes Specification
|
# recipes Specification
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
TBD - created by archiving change tptip-12-recipe-steps. Update Purpose after archive.
|
Каталог помогает выбрать блюдо по фотографии, приготовить его по граммовкам и увидеть приблизительную пищевую ценность порции.
|
||||||
|
|
||||||
## Requirements
|
## Requirements
|
||||||
|
|
||||||
@ -22,3 +22,29 @@ TBD - created by archiving change tptip-12-recipe-steps. Update Purpose after ar
|
|||||||
- **THEN** появляется подтверждение «Блюдо «Овсянка с ягодами» добавлено в приём пищи»
|
- **THEN** появляется подтверждение «Блюдо «Овсянка с ягодами» добавлено в приём пищи»
|
||||||
- **AND** кольца показывают 375 ккал
|
- **AND** кольца показывают 375 ккал
|
||||||
- **AND** в «Питании» запись «1 порц. (340 г) · 375 ккал» с Б/Ж/У
|
- **AND** в «Питании» запись «1 порц. (340 г) · 375 ккал» с Б/Ж/У
|
||||||
|
|
||||||
|
### Requirement: Полный рецепт
|
||||||
|
Система SHALL показывать минимум три рецепта с локальными фото, граммовками сырых ингредиентов, шагами приготовления и приблизительным КБЖУ на порцию на русском, казахском и английском языках.
|
||||||
|
|
||||||
|
#### Scenario: Просмотр рецепта
|
||||||
|
- **GIVEN** выбран русский язык
|
||||||
|
- **WHEN** пользователь открывает /recipes.html
|
||||||
|
- **THEN** видны три блюда, их фотографии, ингредиенты в граммах, шаги и КБЖУ на одну порцию
|
||||||
|
|
||||||
|
#### Scenario: Фото недоступно
|
||||||
|
- **GIVEN** фотография блюда не загрузилась
|
||||||
|
- **WHEN** пользователь просматривает рецепт
|
||||||
|
- **THEN** видна подпись вместо фото, ингредиенты и шаги доступны
|
||||||
|
|
||||||
|
### Requirement: Пересчёт порций
|
||||||
|
Система SHALL пересчитывать граммовки и общее КБЖУ для целого количества порций от 1 до 8, сохраняя КБЖУ на одну порцию.
|
||||||
|
|
||||||
|
#### Scenario: Две порции
|
||||||
|
- **GIVEN** в одной порции овсянки 50 г хлопьев
|
||||||
|
- **WHEN** пользователь выбирает 2 порции
|
||||||
|
- **THEN** показаны 100 г хлопьев, удвоенное общее КБЖУ и неизменное КБЖУ на порцию
|
||||||
|
|
||||||
|
#### Scenario: Нижняя граница
|
||||||
|
- **GIVEN** выбрана 1 порция
|
||||||
|
- **WHEN** пользователь просматривает управление порциями
|
||||||
|
- **THEN** уменьшение количества порций недоступно
|
||||||
|
|||||||
1189
package-lock.json
generated
1189
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
12
package.json
12
package.json
@ -5,12 +5,20 @@
|
|||||||
"type": "commonjs",
|
"type": "commonjs",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"lint": "eslint .",
|
"lint": "eslint .",
|
||||||
"test": "env -u NODE_TEST_CONTEXT node --test tests/*.test.js"
|
"test": "env -u NODE_TEST_CONTEXT node --test tests/*.test.js",
|
||||||
|
"start": "node server.js",
|
||||||
|
"build": "esbuild telemetry-client.js --bundle --minify --outfile=generated/telemetry.js"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
"eslint": "^10.15.0",
|
"eslint": "^10.15.0",
|
||||||
"globals": "^17.14.0",
|
"globals": "^17.14.0",
|
||||||
"jsdom": "^31.0.1"
|
"jsdom": "^31.0.1",
|
||||||
|
"@playwright/test": "^1.56.0",
|
||||||
|
"esbuild": "^0.28.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@sentry/browser": "^11.13.0",
|
||||||
|
"@sentry/node": "^11.13.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
2
playwright.config.js
Normal file
2
playwright.config.js
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
const { defineConfig } = require('@playwright/test');
|
||||||
|
module.exports = defineConfig({ testDir: './tests/browser', use: { baseURL: 'http://127.0.0.1:3093', browserName: 'chromium' }, webServer: { command: 'node server.js', env: { PORT: '3093' }, url: 'http://127.0.0.1:3093/healthz' } });
|
||||||
12
recipes-core.js
Normal file
12
recipes-core.js
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
(function (root) {
|
||||||
|
'use strict';
|
||||||
|
function portions(value) {
|
||||||
|
return Math.min(8, Math.max(1, Math.trunc(Number(value)) || 1));
|
||||||
|
}
|
||||||
|
function nutrition(recipe, foods, count = 1) {
|
||||||
|
return recipe.ingredients.reduce((sum, [id, grams]) => sum.map((v, i) => v + foods[id][i] * grams * portions(count) / 100), [0, 0, 0, 0]);
|
||||||
|
}
|
||||||
|
const api = { portions, nutrition };
|
||||||
|
if (typeof module !== 'undefined') module.exports = api;
|
||||||
|
else root.RecipesCore = api;
|
||||||
|
})(globalThis);
|
||||||
20
recipes-status.i18n.js
Normal file
20
recipes-status.i18n.js
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
globalThis.RecipeMessages = {
|
||||||
|
"ru": {
|
||||||
|
"error": "Не удалось открыть рецепты. Обновите страницу или попробуйте позже.",
|
||||||
|
"retry": "Попробовать снова",
|
||||||
|
"title": "Рецепты на каждый день",
|
||||||
|
"loading": "Загружаем рецепты…"
|
||||||
|
},
|
||||||
|
"kk": {
|
||||||
|
"error": "Рецепттер ашылмады. Бетті жаңартыңыз немесе кейінірек көріңіз.",
|
||||||
|
"retry": "Қайталап көру",
|
||||||
|
"title": "Күнделікті тағам рецептері",
|
||||||
|
"loading": "Рецепттер жүктелуде…"
|
||||||
|
},
|
||||||
|
"en": {
|
||||||
|
"error": "Recipes could not be loaded. Refresh the page or try again later.",
|
||||||
|
"retry": "Try again",
|
||||||
|
"title": "Recipes for every day",
|
||||||
|
"loading": "Loading recipes…"
|
||||||
|
}
|
||||||
|
};
|
||||||
1
recipes.css
Normal file
1
recipes.css
Normal file
@ -0,0 +1 @@
|
|||||||
|
:root{font-family:system-ui,-apple-system,sans-serif;color:#243c33;background:#f5f4ed;font-synthesis:none}*{box-sizing:border-box}body{margin:0}main{max-width:1420px;margin:auto;padding:40px 5vw 60px}header{display:flex;justify-content:space-between;gap:24px;align-items:start;margin-bottom:28px}h1{font-family:Georgia,serif;font-size:clamp(2.5rem,5vw,4.4rem);font-weight:400;line-height:1.06;max-width:700px;margin:18px 0}header p{max-width:650px;line-height:1.6}.eyebrow{text-transform:uppercase;letter-spacing:.15em;font-size:.75rem;font-weight:700;color:#52725c}select,button{font:inherit;color:inherit;background:#fff;border:1px solid #c3ccc1;border-radius:10px;min-height:44px;padding:8px 14px}label{display:grid;gap:8px;font-size:.85rem}button{cursor:pointer}button:disabled{opacity:.35;cursor:default}button:focus-visible,select:focus-visible{outline:3px solid #9b632d;outline-offset:3px}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:24px;align-items:start}article{background:#fff;border-radius:22px;overflow:hidden;border:1px solid #e0e5da}figure{margin:0;background:#e2e8dc;position:relative;min-height:210px}img{width:100%;height:auto;aspect-ratio:1.5;object-fit:cover;display:block}.time{position:absolute;left:18px;bottom:16px;border-radius:20px;background:#fff;padding:7px 12px;font-size:.8rem}.content{padding:24px}h2{font-family:Georgia,serif;font-size:1.9rem;font-weight:400;margin:0 0 22px;line-height:1.2}h3{font-size:1.05rem;margin:26px 0 10px}.servings{display:flex;justify-content:space-between;align-items:center;gap:10px;padding-bottom:16px;border-bottom:1px solid #e3e8de}.controls{display:flex;gap:14px;align-items:center}output{min-width:12px;text-align:center;font-weight:700}.nutrition{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:5px;background:#edf3e8;border-radius:12px;padding:14px 8px;margin:8px 0 0}.nutrition div{text-align:center}.nutrition strong{display:block;font-size:1.1rem}.nutrition span{font-size:.65rem;line-height:1.3;display:block;margin-top:5px}.small{font-size:.78rem;line-height:1.6;color:#536658}.ingredients{list-style:none;padding:0;margin:8px 0}.ingredients li{display:flex;justify-content:space-between;gap:16px;padding:9px 0;border-bottom:1px solid #edf0e8;font-size:.9rem}.ingredients b{white-space:nowrap}ol{padding-left:24px;margin:12px 0 0}ol li{font-size:.9rem;line-height:1.6;padding-left:4px;margin-bottom:12px}ol li::marker{color:#537347;font-weight:700}.note{max-width:850px;margin:28px 0;line-height:1.7;color:#536658;font-size:.85rem}footer{border-top:1px solid #d3ddce;padding-top:24px;font-family:Georgia,serif}.photo-error{padding:28px;line-height:1.6;margin:0}.failure{padding:40px;max-width:600px}.total{margin-top:16px}body[data-loaded="true"] main{animation:appear .3s ease-out}@keyframes appear{from{opacity:0}to{opacity:1}}@media(max-width:1050px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:650px){main{padding:24px 18px 40px}header{display:block}header label{display:flex;align-items:center;margin-top:20px}.grid{grid-template-columns:1fr}h1{font-size:2.7rem}.content{padding:22px}img{aspect-ratio:1.6}}@media(prefers-reduced-motion:reduce){body[data-loaded="true"] main{animation:none}}
|
||||||
152
recipes.data.json
Normal file
152
recipes.data.json
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
{
|
||||||
|
"foods": {
|
||||||
|
"oats": [
|
||||||
|
370,
|
||||||
|
13,
|
||||||
|
7,
|
||||||
|
62
|
||||||
|
],
|
||||||
|
"milk": [
|
||||||
|
52,
|
||||||
|
3,
|
||||||
|
2.5,
|
||||||
|
4.7
|
||||||
|
],
|
||||||
|
"banana": [
|
||||||
|
89,
|
||||||
|
1.1,
|
||||||
|
0.3,
|
||||||
|
22.8
|
||||||
|
],
|
||||||
|
"chicken": [
|
||||||
|
110,
|
||||||
|
23,
|
||||||
|
1.5,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"rice": [
|
||||||
|
350,
|
||||||
|
7,
|
||||||
|
1,
|
||||||
|
78
|
||||||
|
],
|
||||||
|
"broccoli": [
|
||||||
|
34,
|
||||||
|
2.8,
|
||||||
|
0.4,
|
||||||
|
6.6
|
||||||
|
],
|
||||||
|
"oil": [
|
||||||
|
900,
|
||||||
|
0,
|
||||||
|
100,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"water": [
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
"tomato": [
|
||||||
|
18,
|
||||||
|
0.9,
|
||||||
|
0.2,
|
||||||
|
3.9
|
||||||
|
],
|
||||||
|
"cucumber": [
|
||||||
|
15,
|
||||||
|
0.7,
|
||||||
|
0.1,
|
||||||
|
3.6
|
||||||
|
],
|
||||||
|
"feta": [
|
||||||
|
265,
|
||||||
|
14,
|
||||||
|
21,
|
||||||
|
4
|
||||||
|
],
|
||||||
|
"lettuce": [
|
||||||
|
15,
|
||||||
|
1.4,
|
||||||
|
0.2,
|
||||||
|
2.9
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"recipes": [
|
||||||
|
{
|
||||||
|
"id": "oats",
|
||||||
|
"minutes": 12,
|
||||||
|
"ingredients": [
|
||||||
|
[
|
||||||
|
"oats",
|
||||||
|
50
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"milk",
|
||||||
|
150
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"banana",
|
||||||
|
100
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"water",
|
||||||
|
50
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "chicken",
|
||||||
|
"minutes": 30,
|
||||||
|
"ingredients": [
|
||||||
|
[
|
||||||
|
"chicken",
|
||||||
|
150
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"rice",
|
||||||
|
60
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"broccoli",
|
||||||
|
150
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"oil",
|
||||||
|
5
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"water",
|
||||||
|
150
|
||||||
|
]
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "salad",
|
||||||
|
"minutes": 10,
|
||||||
|
"ingredients": [
|
||||||
|
[
|
||||||
|
"tomato",
|
||||||
|
150
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"cucumber",
|
||||||
|
150
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"feta",
|
||||||
|
60
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"lettuce",
|
||||||
|
40
|
||||||
|
],
|
||||||
|
[
|
||||||
|
"oil",
|
||||||
|
5
|
||||||
|
]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
10
recipes.html
Normal file
10
recipes.html
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title></title><link rel="stylesheet" href="/recipes.css">
|
||||||
|
<script defer src="/recipes-status.i18n.js"></script><script defer src="/recipes-core.js"></script><script defer src="/recipes.js"></script>
|
||||||
|
<script defer src="/telemetry.js"></script>
|
||||||
|
</head>
|
||||||
|
<body><main id="app" aria-busy="true"></main></body>
|
||||||
|
</html>
|
||||||
206
recipes.i18n.json
Normal file
206
recipes.i18n.json
Normal file
@ -0,0 +1,206 @@
|
|||||||
|
{
|
||||||
|
"ru": {
|
||||||
|
"title": "Рецепты на каждый день",
|
||||||
|
"intro": "Выберите блюдо, укажите количество порций и готовьте по шагам.",
|
||||||
|
"eyebrow": "Питание • простые идеи",
|
||||||
|
"language": "Язык",
|
||||||
|
"servings": "Порции",
|
||||||
|
"less": "Меньше порций",
|
||||||
|
"more": "Больше порций",
|
||||||
|
"ingredients": "Ингредиенты",
|
||||||
|
"steps": "Как приготовить",
|
||||||
|
"perServing": "На одну порцию, примерно",
|
||||||
|
"total": "На всё блюдо, примерно",
|
||||||
|
"nutrition": [
|
||||||
|
"ккал",
|
||||||
|
"Белки, г",
|
||||||
|
"Жиры, г",
|
||||||
|
"Углеводы, г"
|
||||||
|
],
|
||||||
|
"grams": "г",
|
||||||
|
"minutes": "мин",
|
||||||
|
"note": "Вес указан для сырых продуктов. Пищевая ценность приблизительная и зависит от выбранных продуктов. Фото иллюстрируют блюдо.",
|
||||||
|
"photo": "Фото блюда недоступно. Используйте состав и шаги приготовления.",
|
||||||
|
"error": "Не удалось открыть рецепты. Обновите страницу или попробуйте позже.",
|
||||||
|
"retry": "Попробовать снова",
|
||||||
|
"loading": "Загружаем рецепты…",
|
||||||
|
"raw": "Вес до приготовления",
|
||||||
|
"footer": "Простые продукты. Понятные шаги. Ваш ритм.",
|
||||||
|
"recipes": {
|
||||||
|
"oats": {
|
||||||
|
"title": "Овсянка с бананом",
|
||||||
|
"steps": [
|
||||||
|
"Смешайте хлопья, молоко и воду в небольшой кастрюле.",
|
||||||
|
"Доведите до кипения и варите на слабом огне 5–7 минут, помешивая.",
|
||||||
|
"Нарежьте банан и добавьте в готовую кашу."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"chicken": {
|
||||||
|
"title": "Курица с рисом и брокколи",
|
||||||
|
"steps": [
|
||||||
|
"Промойте рис, залейте водой и варите под крышкой около 15–20 минут до мягкости.",
|
||||||
|
"Нарежьте курицу небольшими кусочками. Смажьте сковороду маслом и готовьте курицу 10–15 минут, переворачивая, до полной готовности (74 °C внутри).",
|
||||||
|
"Приготовьте брокколи на пару 5–7 минут до мягкости и подайте с курицей и рисом."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"salad": {
|
||||||
|
"title": "Овощной салат с фетой",
|
||||||
|
"steps": [
|
||||||
|
"Вымойте и обсушите овощи и листья салата.",
|
||||||
|
"Нарежьте помидор, огурец и фету, порвите листья салата.",
|
||||||
|
"Соедините ингредиенты, заправьте маслом и аккуратно перемешайте."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foods": {
|
||||||
|
"oats": "Овсяные хлопья",
|
||||||
|
"milk": "Молоко 2,5%",
|
||||||
|
"banana": "Банан без кожуры",
|
||||||
|
"chicken": "Куриная грудка без кожи",
|
||||||
|
"rice": "Рис сухой",
|
||||||
|
"broccoli": "Брокколи",
|
||||||
|
"oil": "Оливковое масло",
|
||||||
|
"water": "Вода",
|
||||||
|
"tomato": "Помидор",
|
||||||
|
"cucumber": "Огурец",
|
||||||
|
"feta": "Сыр фета",
|
||||||
|
"lettuce": "Листья салата"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"kk": {
|
||||||
|
"title": "Күнделікті тағам рецептері",
|
||||||
|
"intro": "Тағамды таңдап, порция санын көрсетіңіз де, қадамдар бойынша дайындаңыз.",
|
||||||
|
"eyebrow": "Тамақтану • оңай идеялар",
|
||||||
|
"language": "Тіл",
|
||||||
|
"servings": "Порциялар",
|
||||||
|
"less": "Порцияны азайту",
|
||||||
|
"more": "Порцияны көбейту",
|
||||||
|
"ingredients": "Ингредиенттер",
|
||||||
|
"steps": "Дайындау жолы",
|
||||||
|
"perServing": "Бір порцияға, шамамен",
|
||||||
|
"total": "Барлық тағамға, шамамен",
|
||||||
|
"nutrition": [
|
||||||
|
"ккал",
|
||||||
|
"Ақуыз, г",
|
||||||
|
"Май, г",
|
||||||
|
"Көмірсу, г"
|
||||||
|
],
|
||||||
|
"grams": "г",
|
||||||
|
"minutes": "мин",
|
||||||
|
"note": "Салмақ шикі өнімдер үшін көрсетілген. Тағамдық құндылық шамамен берілген және таңдалған өнімдерге байланысты. Фотосуреттер тағамды бейнелейді.",
|
||||||
|
"photo": "Тағам фотосы ашылмады. Құрамы мен дайындау қадамдарын пайдаланыңыз.",
|
||||||
|
"error": "Рецепттер ашылмады. Бетті жаңартыңыз немесе кейінірек көріңіз.",
|
||||||
|
"retry": "Қайталап көру",
|
||||||
|
"loading": "Рецепттер жүктелуде…",
|
||||||
|
"raw": "Пісіргенге дейінгі салмақ",
|
||||||
|
"footer": "Қарапайым өнімдер. Түсінікті қадамдар. Өз ырғағыңыз.",
|
||||||
|
"recipes": {
|
||||||
|
"oats": {
|
||||||
|
"title": "Банан қосылған сұлы ботқасы",
|
||||||
|
"steps": [
|
||||||
|
"Үлпектерді, сүтті және суды шағын кәстрөлге салыңыз.",
|
||||||
|
"Қайнатып, баяу отта 5–7 минут араластырып пісіріңіз.",
|
||||||
|
"Бананды турап, дайын ботқаға қосыңыз."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"chicken": {
|
||||||
|
"title": "Күріш пен брокколи қосылған тауық еті",
|
||||||
|
"steps": [
|
||||||
|
"Күрішті жуып, су құйыңыз. Қақпағын жауып, жұмсарғанша 15–20 минут пісіріңіз.",
|
||||||
|
"Тауық етін шағын бөліктерге кесіңіз. Табаға май жағып, етті аударып отырып 10–15 минут толық піскенше қуырыңыз (ішкі температурасы 74 °C).",
|
||||||
|
"Брокколиді 5–7 минут буға пісіріп, тауық еті және күрішпен ұсыныңыз."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"salad": {
|
||||||
|
"title": "Фета қосылған көкөніс салаты",
|
||||||
|
"steps": [
|
||||||
|
"Көкөністер мен салат жапырақтарын жуып, құрғатыңыз.",
|
||||||
|
"Қызанақ, қияр және фетаны турап, салат жапырақтарын үзіңіз.",
|
||||||
|
"Барлығын араластырып, май қосыңыз да, абайлап араластырыңыз."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foods": {
|
||||||
|
"oats": "Сұлы үлпектері",
|
||||||
|
"milk": "Сүт 2,5%",
|
||||||
|
"banana": "Қабығы аршылған банан",
|
||||||
|
"chicken": "Терісіз тауық төс еті",
|
||||||
|
"rice": "Құрғақ күріш",
|
||||||
|
"broccoli": "Брокколи",
|
||||||
|
"oil": "Зәйтүн майы",
|
||||||
|
"water": "Су",
|
||||||
|
"tomato": "Қызанақ",
|
||||||
|
"cucumber": "Қияр",
|
||||||
|
"feta": "Фета ірімшігі",
|
||||||
|
"lettuce": "Салат жапырақтары"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"en": {
|
||||||
|
"title": "Recipes for every day",
|
||||||
|
"intro": "Choose a dish, set your servings and follow the cooking steps.",
|
||||||
|
"eyebrow": "Nutrition • simple ideas",
|
||||||
|
"language": "Language",
|
||||||
|
"servings": "Servings",
|
||||||
|
"less": "Fewer servings",
|
||||||
|
"more": "More servings",
|
||||||
|
"ingredients": "Ingredients",
|
||||||
|
"steps": "How to cook",
|
||||||
|
"perServing": "Per serving, approximately",
|
||||||
|
"total": "Whole dish, approximately",
|
||||||
|
"nutrition": [
|
||||||
|
"kcal",
|
||||||
|
"Protein, g",
|
||||||
|
"Fat, g",
|
||||||
|
"Carbs, g"
|
||||||
|
],
|
||||||
|
"grams": "g",
|
||||||
|
"minutes": "min",
|
||||||
|
"note": "Weights are for raw ingredients. Nutrition is approximate and varies with the products you use. Photos illustrate the dish.",
|
||||||
|
"photo": "The dish photo could not load. Use the ingredients and cooking steps.",
|
||||||
|
"error": "Recipes could not be loaded. Refresh the page or try again later.",
|
||||||
|
"retry": "Try again",
|
||||||
|
"loading": "Loading recipes…",
|
||||||
|
"raw": "Weight before cooking",
|
||||||
|
"footer": "Simple ingredients. Clear steps. Your rhythm.",
|
||||||
|
"recipes": {
|
||||||
|
"oats": {
|
||||||
|
"title": "Banana porridge",
|
||||||
|
"steps": [
|
||||||
|
"Combine oats, milk and water in a small saucepan.",
|
||||||
|
"Bring to a simmer and cook gently for 5–7 minutes, stirring.",
|
||||||
|
"Slice the banana and add it to the cooked porridge."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"chicken": {
|
||||||
|
"title": "Chicken, rice & broccoli",
|
||||||
|
"steps": [
|
||||||
|
"Rinse the rice, add the water and simmer covered for about 15–20 minutes until tender.",
|
||||||
|
"Cut the chicken into small pieces. Oil a pan and cook for 10–15 minutes, turning, until fully cooked (74 °C in the centre).",
|
||||||
|
"Steam the broccoli for 5–7 minutes until tender and serve with the chicken and rice."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"salad": {
|
||||||
|
"title": "Vegetable & feta salad",
|
||||||
|
"steps": [
|
||||||
|
"Wash and dry the vegetables and lettuce.",
|
||||||
|
"Chop the tomato, cucumber and feta, and tear the lettuce.",
|
||||||
|
"Combine everything, drizzle with oil and toss gently."
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"foods": {
|
||||||
|
"oats": "Rolled oats",
|
||||||
|
"milk": "Milk, 2.5% fat",
|
||||||
|
"banana": "Peeled banana",
|
||||||
|
"chicken": "Skinless chicken breast",
|
||||||
|
"rice": "Dry rice",
|
||||||
|
"broccoli": "Broccoli",
|
||||||
|
"oil": "Olive oil",
|
||||||
|
"water": "Water",
|
||||||
|
"tomato": "Tomato",
|
||||||
|
"cucumber": "Cucumber",
|
||||||
|
"feta": "Feta cheese",
|
||||||
|
"lettuce": "Lettuce"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
102
recipes.js
Normal file
102
recipes.js
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
/* global RecipesCore, RecipeMessages */
|
||||||
|
'use strict';
|
||||||
|
const app = document.getElementById('app');
|
||||||
|
const names = { ru: 'Русский', kk: 'Қазақша', en: 'English' };
|
||||||
|
const requested = new URLSearchParams(location.search).get('lang') || navigator.language.split('-')[0];
|
||||||
|
let lang = Object.hasOwn(names, requested) ? requested : 'ru';
|
||||||
|
document.documentElement.lang = lang;
|
||||||
|
document.title = RecipeMessages[lang].title;
|
||||||
|
app.textContent = RecipeMessages[lang].loading;
|
||||||
|
let data, translations;
|
||||||
|
const counts = new Map();
|
||||||
|
const e = (tag, text, className) => {
|
||||||
|
const node = document.createElement(tag);
|
||||||
|
if (text != null) node.textContent = text;
|
||||||
|
if (className) node.className = className;
|
||||||
|
return node;
|
||||||
|
};
|
||||||
|
function nutrients(values, t) {
|
||||||
|
const box = e('div', null, 'nutrition');
|
||||||
|
values.forEach((value, i) => {
|
||||||
|
const cell = e('div');
|
||||||
|
cell.append(e('strong', new Intl.NumberFormat(lang, { maximumFractionDigits: i ? 1 : 0 }).format(value)), e('span', t.nutrition[i]));
|
||||||
|
box.append(cell);
|
||||||
|
});
|
||||||
|
return box;
|
||||||
|
}
|
||||||
|
function card(recipe, t) {
|
||||||
|
const count = counts.get(recipe.id) || 1;
|
||||||
|
const text = t.recipes[recipe.id];
|
||||||
|
const article = e('article'); article.dataset.recipe = recipe.id;
|
||||||
|
const figure = e('figure');
|
||||||
|
const img = e('img'); img.src = `/assets/${recipe.id}.jpg`; img.alt = text.title; img.width = 900; img.height = 600;
|
||||||
|
img.addEventListener('error', () => { img.replaceWith(e('p', t.photo, 'photo-error')); });
|
||||||
|
figure.append(img, e('span', `${recipe.minutes} ${t.minutes}`, 'time'));
|
||||||
|
const content = e('div', null, 'content');
|
||||||
|
const title = e('h2', text.title); title.id = `title-${recipe.id}`;
|
||||||
|
article.setAttribute('aria-labelledby', title.id);
|
||||||
|
const controls = e('div', null, 'controls');
|
||||||
|
const minus = e('button', '−'); minus.type = 'button'; minus.setAttribute('aria-label', t.less); minus.disabled = count === 1;
|
||||||
|
const plus = e('button', '+'); plus.type = 'button'; plus.setAttribute('aria-label', t.more); plus.disabled = count === 8;
|
||||||
|
const output = e('output', count); output.setAttribute('aria-live', 'polite'); output.setAttribute('aria-label', t.servings);
|
||||||
|
const change = (delta) => {
|
||||||
|
counts.set(recipe.id, RecipesCore.portions(count + delta));
|
||||||
|
const replacement = card(recipe, translations[lang]);
|
||||||
|
article.replaceWith(replacement);
|
||||||
|
const buttons = replacement.querySelectorAll('.controls button');
|
||||||
|
const target = buttons[delta < 0 ? 0 : 1];
|
||||||
|
(target.disabled ? buttons[delta < 0 ? 1 : 0] : target).focus();
|
||||||
|
};
|
||||||
|
minus.onclick = () => change(-1); plus.onclick = () => change(1);
|
||||||
|
controls.append(minus, output, plus);
|
||||||
|
const servings = e('div', null, 'servings'); servings.append(e('span', t.servings), controls);
|
||||||
|
const ingredients = e('ul', null, 'ingredients');
|
||||||
|
for (const [id, grams] of recipe.ingredients) {
|
||||||
|
const item = e('li'); item.append(e('span', t.foods[id]), e('b', `${grams * count} ${t.grams}`)); ingredients.append(item);
|
||||||
|
}
|
||||||
|
const steps = e('ol'); for (const step of text.steps) steps.append(e('li', step));
|
||||||
|
content.append(title, servings, e('p', t.perServing, 'small'), nutrients(RecipesCore.nutrition(recipe, data.foods), t));
|
||||||
|
if (count > 1) content.append(e('p', t.total, 'small total'), nutrients(RecipesCore.nutrition(recipe, data.foods, count), t));
|
||||||
|
content.append(e('h3', t.ingredients), e('p', t.raw, 'small'), ingredients, e('h3', t.steps), steps);
|
||||||
|
article.append(figure, content); return article;
|
||||||
|
}
|
||||||
|
function render() {
|
||||||
|
const t = translations[lang];
|
||||||
|
document.documentElement.lang = lang; document.title = t.title;
|
||||||
|
const header = e('header'), intro = e('div');
|
||||||
|
intro.append(e('p', t.eyebrow, 'eyebrow'), e('h1', t.title), e('p', t.intro));
|
||||||
|
const label = e('label', t.language), select = e('select');
|
||||||
|
select.id = 'language';
|
||||||
|
for (const [code, name] of Object.entries(names)) {
|
||||||
|
const option = e('option', name); option.value = code; option.selected = code === lang; select.append(option);
|
||||||
|
}
|
||||||
|
select.onchange = () => {
|
||||||
|
lang = select.value;
|
||||||
|
const url = new URL(location.href); url.searchParams.set('lang', lang); history.replaceState(null, '', url);
|
||||||
|
render(); document.getElementById('language').focus();
|
||||||
|
};
|
||||||
|
label.append(select); header.append(intro, label);
|
||||||
|
const grid = e('div', null, 'grid'); for (const recipe of data.recipes) grid.append(card(recipe, t));
|
||||||
|
app.replaceChildren(header, grid, e('p', t.note, 'note'), e('footer', t.footer));
|
||||||
|
app.setAttribute('aria-busy', 'false'); document.body.dataset.loaded = 'true';
|
||||||
|
}
|
||||||
|
async function load() {
|
||||||
|
app.setAttribute('aria-busy', 'true');
|
||||||
|
try {
|
||||||
|
const responses = await Promise.all(['/recipes.data.json', '/recipes.i18n.json'].map(url => fetch(url)));
|
||||||
|
if (responses.some(response => !response.ok)) throw new Error('catalog unavailable');
|
||||||
|
[data, translations] = await Promise.all(responses.map(response => response.json()));
|
||||||
|
render();
|
||||||
|
} catch {
|
||||||
|
// Error text lives in the translation resource, including the offline fallback.
|
||||||
|
const fallback = RecipeMessages;
|
||||||
|
app.replaceChildren();
|
||||||
|
if (fallback) {
|
||||||
|
const box = e('div', null, 'failure'); box.setAttribute('role', 'alert');
|
||||||
|
const retry = e('button', fallback[lang].retry); retry.onclick = load;
|
||||||
|
box.append(e('p', fallback[lang].error), retry); app.append(box);
|
||||||
|
}
|
||||||
|
app.setAttribute('aria-busy', 'false');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
load();
|
||||||
22
server.js
22
server.js
@ -1,5 +1,8 @@
|
|||||||
|
const Sentry = require('@sentry/node');
|
||||||
|
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 });
|
||||||
// Мини-сервер стенда (TPTIP-6): слушает $PORT, /healthz → 200, отдаёт файлы приложения по белому списку.
|
// Мини-сервер стенда (TPTIP-6): слушает $PORT, /healthz → 200, отдаёт файлы приложения по белому списку.
|
||||||
// Английской страницы-заглушки нет (TPTIP-11): по ссылке всегда открывается трекер.
|
// По ссылке открывается трекер; каталог рецептов доступен на /recipes.html.
|
||||||
|
|
||||||
const http = require('node:http');
|
const http = require('node:http');
|
||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
const path = require('node:path');
|
const path = require('node:path');
|
||||||
@ -11,7 +14,18 @@ const FILES = {
|
|||||||
'/index.html': ['index.html', 'text/html; charset=utf-8'],
|
'/index.html': ['index.html', 'text/html; charset=utf-8'],
|
||||||
'/manifest.webmanifest': ['manifest.webmanifest', 'application/manifest+json'],
|
'/manifest.webmanifest': ['manifest.webmanifest', 'application/manifest+json'],
|
||||||
'/sw.js': ['sw.js', 'text/javascript; charset=utf-8'],
|
'/sw.js': ['sw.js', 'text/javascript; charset=utf-8'],
|
||||||
'/icon.svg': ['icon.svg', 'image/svg+xml']
|
'/icon.svg': ['icon.svg', 'image/svg+xml'],
|
||||||
|
'/recipes.html': ['recipes.html', 'text/html; charset=utf-8'],
|
||||||
|
'/recipes.css': ['recipes.css', 'text/css; charset=utf-8'],
|
||||||
|
'/telemetry.js': ['generated/telemetry.js', 'text/javascript; charset=utf-8'],
|
||||||
|
'/recipes.js': ['recipes.js', 'text/javascript; charset=utf-8'],
|
||||||
|
'/recipes-core.js': ['recipes-core.js', 'text/javascript; charset=utf-8'],
|
||||||
|
'/recipes.data.json': ['recipes.data.json', 'application/json; charset=utf-8'],
|
||||||
|
'/recipes.i18n.json': ['recipes.i18n.json', 'application/json; charset=utf-8'],
|
||||||
|
'/recipes-status.i18n.js': ['recipes-status.i18n.js', 'text/javascript; charset=utf-8'],
|
||||||
|
'/assets/oats.jpg': ['assets/oats.jpg', 'image/jpeg'],
|
||||||
|
'/assets/chicken.jpg': ['assets/chicken.jpg', 'image/jpeg'],
|
||||||
|
'/assets/salad.jpg': ['assets/salad.jpg', 'image/jpeg']
|
||||||
};
|
};
|
||||||
|
|
||||||
function send(res, f) {
|
function send(res, f) {
|
||||||
@ -27,6 +41,10 @@ function createServer() {
|
|||||||
return http.createServer((req, res) => {
|
return http.createServer((req, res) => {
|
||||||
const url = (req.url || '/').split('?')[0];
|
const url = (req.url || '/').split('?')[0];
|
||||||
if (url === '/healthz') { res.writeHead(200, { 'content-type': 'text/plain' }); return res.end('ok'); }
|
if (url === '/healthz') { res.writeHead(200, { 'content-type': 'text/plain' }); return res.end('ok'); }
|
||||||
|
if (url === '/telemetry.json') {
|
||||||
|
res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
||||||
|
return res.end(JSON.stringify({ dsn: process.env.PUBLIC_SENTRY_DSN || '', release: process.env.SENTRY_RELEASE, environment: process.env.SENTRY_ENVIRONMENT || 'dev' }));
|
||||||
|
}
|
||||||
const f = FILES[url];
|
const f = FILES[url];
|
||||||
if (!f) { res.writeHead(404); return res.end('not found'); }
|
if (!f) { res.writeHead(404); return res.end('not found'); }
|
||||||
send(res, f);
|
send(res, f);
|
||||||
|
|||||||
4
sw.js
4
sw.js
@ -1,6 +1,6 @@
|
|||||||
// Сервис-воркер: приложение открывается без интернета (сначала сеть, при отсутствии — копия из кэша).
|
// Сервис-воркер: приложение открывается без интернета (сначала сеть, при отсутствии — копия из кэша).
|
||||||
const CACHE = 'tpt-v4-wizard';
|
const CACHE = 'tpt-v5-wizard-recipes';
|
||||||
const FILES = ['./', 'index.html', 'gym-plan.i18n.js', 'manifest.webmanifest', 'icon.svg'];
|
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 => {
|
||||||
e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k)))).then(() => self.clients.claim()));
|
e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k !== CACHE).map(k => caches.delete(k)))).then(() => self.clients.claim()));
|
||||||
|
|||||||
4
telemetry-client.js
Normal file
4
telemetry-client.js
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
import * as Sentry from '@sentry/browser';
|
||||||
|
fetch('/telemetry.json').then(response => response.json()).then(config => {
|
||||||
|
if (config.dsn) Sentry.init({ ...config, sendDefaultPii: false });
|
||||||
|
}).catch(() => { /* Optional telemetry must not prevent opening recipes. */ });
|
||||||
48
tests/browser/recipes.spec.js
Normal file
48
tests/browser/recipes.spec.js
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
const { test, expect } = require('@playwright/test');
|
||||||
|
test('Три рецепта, две порции, границы и перевод без потери выбора', async ({ page }) => {
|
||||||
|
await page.goto('/recipes.html?lang=ru');
|
||||||
|
await expect(page.locator('article')).toHaveCount(3);
|
||||||
|
const oats = page.locator('[data-recipe=oats]');
|
||||||
|
await expect(oats.getByRole('button', { name: 'Меньше порций' })).toBeDisabled();
|
||||||
|
await oats.getByRole('button', { name: 'Больше порций' }).click();
|
||||||
|
await expect(oats.locator('output')).toHaveText('2');
|
||||||
|
await expect(oats.locator('.ingredients li').first()).toContainText('100 г');
|
||||||
|
await expect(oats.locator('.nutrition').first().locator('strong').first()).toHaveText('352');
|
||||||
|
await expect(oats.locator('.nutrition').nth(1).locator('strong').first()).toHaveText('704');
|
||||||
|
for (let i = 0; i < 6; i++) await oats.getByRole('button', { name: 'Больше порций' }).click();
|
||||||
|
await expect(oats.getByRole('button', { name: 'Больше порций' })).toBeDisabled();
|
||||||
|
for (const [lang, title] of [['kk', 'Күнделікті тағам рецептері'], ['en', 'Recipes for every day'], ['ru', 'Рецепты на каждый день']]) {
|
||||||
|
await page.locator('select').selectOption(lang); await expect(page.locator('h1')).toHaveText(title); await expect(oats.locator('output')).toHaveText('8');
|
||||||
|
}
|
||||||
|
for (const img of await page.locator('img').all()) expect(await img.evaluate(img => img.naturalWidth)).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
test('Фото недоступно: состав и шаги остаются видимыми', async ({ page }) => {
|
||||||
|
await page.route('**/assets/oats.jpg', route => route.abort());
|
||||||
|
await page.goto('/recipes.html?lang=ru');
|
||||||
|
const oats = page.locator('[data-recipe=oats]');
|
||||||
|
await expect(oats.getByText('Фото блюда недоступно.', { exact: false })).toBeVisible();
|
||||||
|
await expect(oats.locator('ol li')).toHaveCount(3);
|
||||||
|
});
|
||||||
|
test('Ошибка загрузки: понятное сообщение и повторная попытка', async ({ page }) => {
|
||||||
|
await page.route('**/recipes.data.json', route => route.fulfill({ status: 503, body: '' }));
|
||||||
|
await page.goto('/recipes.html?lang=ru');
|
||||||
|
await expect(page.getByRole('alert')).toContainText('Не удалось открыть рецепты. Обновите страницу или попробуйте позже.');
|
||||||
|
await page.unroute('**/recipes.data.json');
|
||||||
|
await page.getByRole('button', { name: 'Попробовать снова' }).click();
|
||||||
|
await expect(page.locator('article')).toHaveCount(3);
|
||||||
|
});
|
||||||
|
test('Узкий экран: тексты видимы, горизонтальной прокрутки нет', async ({ page }) => {
|
||||||
|
await page.setViewportSize({ width: 375, height: 812 });
|
||||||
|
await page.goto('/recipes.html?lang=kk');
|
||||||
|
await expect(page.locator('article')).toHaveCount(3);
|
||||||
|
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBeTruthy();
|
||||||
|
await page.screenshot({ path: '/tmp/tptip-3-mobile.png', fullPage: true, animations: 'disabled' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Переход из трекера в каталог рецептов', async ({ page }) => {
|
||||||
|
await page.addInitScript(() => localStorage.setItem('tpt.v1', JSON.stringify({ v: 1, settings: { onboarded: true } })));
|
||||||
|
await page.goto('/');
|
||||||
|
await page.getByRole('link', { name: 'Рецепты на каждый день' }).first().click();
|
||||||
|
await expect(page.locator('article')).toHaveCount(3);
|
||||||
|
await expect(page).toHaveURL(/recipes.html/);
|
||||||
|
});
|
||||||
14
tests/recipes-server.test.js
Normal file
14
tests/recipes-server.test.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
const { test } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createServer } = require('../server');
|
||||||
|
test('Каталог доступен по ссылке, ресурсы локальны, закрытые файлы недоступны', async () => {
|
||||||
|
const server = createServer();
|
||||||
|
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||||
|
const base = `http://127.0.0.1:${server.address().port}`;
|
||||||
|
try {
|
||||||
|
for (const path of ['/', '/recipes.html', '/recipes.css', '/recipes.js', '/recipes-core.js', '/recipes.i18n.json', '/recipes.data.json', '/recipes-status.i18n.js', '/assets/oats.jpg', '/assets/chicken.jpg', '/assets/salad.jpg', '/healthz']) {
|
||||||
|
const res = await fetch(base + path); assert.equal(res.status, 200, path); assert.ok((await res.arrayBuffer()).byteLength > 0);
|
||||||
|
}
|
||||||
|
for (const path of ['/.env', '/server.js', '/.peppa/project.json', '/assets/README.md', '/unknown']) assert.equal((await fetch(base + path)).status, 404);
|
||||||
|
} finally { await new Promise(resolve => server.close(resolve)); }
|
||||||
|
});
|
||||||
34
tests/recipes.test.js
Normal file
34
tests/recipes.test.js
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
const { test } = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const data = require('../recipes.data.json');
|
||||||
|
const translations = require('../recipes.i18n.json');
|
||||||
|
const { portions, nutrition } = require('../recipes-core');
|
||||||
|
test('Просмотр рецепта: три полных рецепта на каждом языке с локальными фото', () => {
|
||||||
|
assert.equal(data.recipes.length, 3);
|
||||||
|
for (const recipe of data.recipes) {
|
||||||
|
const image = fs.readFileSync(`assets/${recipe.id}.jpg`);
|
||||||
|
assert.equal(image.readUInt16BE(), 0xffd8);
|
||||||
|
assert.ok(image.length > 10000);
|
||||||
|
for (const lang of ['ru', 'kk', 'en']) {
|
||||||
|
const t = translations[lang];
|
||||||
|
assert.ok(t.recipes[recipe.id].title);
|
||||||
|
assert.ok(t.recipes[recipe.id].steps.length >= 3);
|
||||||
|
for (const [id, grams] of recipe.ingredients) {
|
||||||
|
assert.ok(t.foods[id]); assert.ok(grams > 0); assert.equal(data.foods[id].length, 4);
|
||||||
|
}
|
||||||
|
assert.deepEqual(Object.keys(t).sort(), Object.keys(translations.ru).sort());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
test('Две порции: 100 г хлопьев и удвоенное общее КБЖУ', () => {
|
||||||
|
const oats = data.recipes[0];
|
||||||
|
assert.equal(oats.ingredients[0][1] * portions(2), 100);
|
||||||
|
const one = nutrition(oats, data.foods);
|
||||||
|
assert.ok(Math.abs(one[0] - 352) < .01);
|
||||||
|
assert.deepEqual(nutrition(oats, data.foods, 2), one.map(v => v * 2));
|
||||||
|
});
|
||||||
|
test('Границы количества порций: от 1 до 8, только целые числа', () => {
|
||||||
|
for (const v of [-1, 0, '', 'oops', null]) assert.equal(portions(v), 1);
|
||||||
|
assert.equal(portions(20), 8); assert.equal(portions(2.9), 2);
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue
Block a user