SSGSD-4: веб-сервис со страницей продукта, /healthz, проверки
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0dd33a65aa
commit
d5d989fb19
9
.dockerignore
Normal file
9
.dockerignore
Normal file
@ -0,0 +1,9 @@
|
||||
node_modules
|
||||
dist
|
||||
dist-test
|
||||
.git
|
||||
.env
|
||||
.env.local
|
||||
.claude
|
||||
openspec
|
||||
.pnpm-store
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@ -2,3 +2,6 @@ node_modules/
|
||||
.env
|
||||
.env.local
|
||||
.DS_Store
|
||||
dist/
|
||||
dist-test/
|
||||
.pnpm-store/
|
||||
|
||||
@ -1 +1,19 @@
|
||||
{"slug":"sdelat-shablonnyy-grafik-smennosti-dlya","key":"SSGSD","name":"Сделать шаблонный график сменности для инсталляторов","peppaUrl":"https://peppa.telecom.quest"}
|
||||
{
|
||||
"slug": "sdelat-shablonnyy-grafik-smennosti-dlya",
|
||||
"key": "SSGSD",
|
||||
"name": "Сделать шаблонный график сменности для инсталляторов",
|
||||
"peppaUrl": "https://peppa.telecom.quest",
|
||||
"checks": {
|
||||
"install": "pnpm install --frozen-lockfile",
|
||||
"lint": "pnpm lint",
|
||||
"typecheck": "pnpm typecheck",
|
||||
"test": "pnpm test",
|
||||
"build": "pnpm build"
|
||||
},
|
||||
"deploy": {
|
||||
"compose": "deploy/compose.yml",
|
||||
"service": "web",
|
||||
"port": 3000,
|
||||
"health": "/healthz"
|
||||
}
|
||||
}
|
||||
|
||||
7
biome.json
Normal file
7
biome.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
|
||||
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
|
||||
"files": { "includes": ["src/**", "test/**", "*.json"] },
|
||||
"formatter": { "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 },
|
||||
"linter": { "enabled": true }
|
||||
}
|
||||
@ -39,8 +39,9 @@
|
||||
| de | ru |
|
||||
|
||||
### Requirement: Расчёт ротации шаблона
|
||||
Сервис SHALL раскладывать шаблон графика по дням для списка людей, сдвигая начало шаблона
|
||||
так, чтобы люди делились на группы по числу фаз шаблона.
|
||||
Сервис SHALL раскладывать шаблон графика по дням для списка людей (ротация): люди по порядку
|
||||
делятся на группы, число групп — длина шаблона, делённая на число рабочих дней (с округлением,
|
||||
не меньше одной), и у каждой следующей группы начало шаблона сдвинуто на равную долю его длины.
|
||||
|
||||
#### Scenario: Шаблон 2/2 на четверых
|
||||
- **GIVEN** шаблон «Р Р В В» и люди Айдос, Марат, Ержан, Дмитрий
|
||||
|
||||
22
package.json
Normal file
22
package.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "shift-schedule",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc -p tsconfig.build.json",
|
||||
"start": "node dist/index.js",
|
||||
"lint": "biome check .",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "rm -rf dist-test && tsc -p tsconfig.test.json && node --test 'dist-test/test/**/*.test.js'"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^2.6.8",
|
||||
"@types/node": "^22.20.5",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"packageManager": "pnpm@10.34.9"
|
||||
}
|
||||
154
pnpm-lock.yaml
generated
Normal file
154
pnpm-lock.yaml
generated
Normal file
@ -0,0 +1,154 @@
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
devDependencies:
|
||||
'@biomejs/biome':
|
||||
specifier: ^2.6.8
|
||||
version: 2.6.8
|
||||
'@types/node':
|
||||
specifier: ^22.20.5
|
||||
version: 22.20.5
|
||||
typescript:
|
||||
specifier: ^5.9.3
|
||||
version: 5.9.3
|
||||
|
||||
packages:
|
||||
|
||||
'@biomejs/biome@2.6.8':
|
||||
resolution: {integrity: sha512-kqZUFvX6/aYQOmzfRN5ANcfNS9wLH4aHLWWP/dQKyhRZVoA6rdWszA7DGugFcxPbMiznUyVYyukVl+ExZN4PQA==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
hasBin: true
|
||||
|
||||
'@biomejs/cli-android-arm64@2.6.8':
|
||||
resolution: {integrity: sha512-X4JKPLK85kfUTwuuaORFplnBfGjKkp62PsFhhcL7F/Tpltc7pyUofjlkkMnlZZLWsifFl7LNB8ngVrwJg1uo1Q==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
|
||||
'@biomejs/cli-android-x64@2.6.8':
|
||||
resolution: {integrity: sha512-C3Hk485vl+deEj53K08+SYYelPIPkdSZL3qHuD31Xi+qydVa4q2ze+aCYo1k3iJGWtvWtjHaGkDh7S2sX6wk8w==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [x64]
|
||||
os: [android]
|
||||
|
||||
'@biomejs/cli-darwin-arm64@2.6.8':
|
||||
resolution: {integrity: sha512-DHyj+JnRHcn4YdvpiqgTFZMYKSPELMCfFpNNlEuu1L8DKTGXhzW7raIwdsbo2Ie9nCljQLAQkVWQk/mwM0ueiA==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@biomejs/cli-darwin-x64@2.6.8':
|
||||
resolution: {integrity: sha512-QWWUPjlA0RnkkgYnFLUHZu+RrDc0FdK0A+wEPA+dENQJwsuSHMH89lspnAw2QUWWc9VHyfluGx1Xmp6Y2GZi8Q==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@biomejs/cli-linux-arm64-musl@2.6.8':
|
||||
resolution: {integrity: sha512-WB9PhOitX+bRc0G3+GNJGlvbKoWn3JoB9z4E04JQizIC9aPCQyIvwvWG7QZHxw6k20Fi+dHLmZ2fSEmBa9HqiA==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@biomejs/cli-linux-arm64@2.6.8':
|
||||
resolution: {integrity: sha512-0Bjim8lKwnrvXUHoI4k3Tb51BjoiLEwDnovCI8nSzkk6wj3dShiuAjrx6+X0Hjf4ejR1sRZgTQiSDHlpy9vB7w==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@biomejs/cli-linux-x64-musl@2.6.8':
|
||||
resolution: {integrity: sha512-64Yzo+J4fEk7Kf9SMnVdVxC+Y2A2e/L86QTP9JjGQ57lsddyELLpbBcNMxSJggre2T1AvISwwSrOApkBAHDqNA==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [musl]
|
||||
|
||||
'@biomejs/cli-linux-x64@2.6.8':
|
||||
resolution: {integrity: sha512-XIk3pLQT56I6Tti+u0DF8FtSNXjCMTPbxVTzfJ9cS2t1ImVKvrqV5b52GuEaJg6/wuiXvz0sjfb5saB4TPRjzA==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
libc: [glibc]
|
||||
|
||||
'@biomejs/cli-win32-arm64@2.6.8':
|
||||
resolution: {integrity: sha512-ezjCEZzHIWE2pdh83a7zLVcAAcDaERcTcvfA7uWlxqz/1CuDxgtfO19pDg9B6YY4wKYIDvYBw2QCMnqIshSwmw==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@biomejs/cli-win32-x64@2.6.8':
|
||||
resolution: {integrity: sha512-cD6HvGczZUiAYsY8s2TxxXj2AHFzEdMomvVJfEjzOjBM45nGqIDfBpbtvwGQzDCN8X2yKKk9u1jnDZisT2nxIg==}
|
||||
engines: {node: '>=14.21.3'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@types/node@22.20.5':
|
||||
resolution: {integrity: sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==}
|
||||
|
||||
typescript@5.9.3:
|
||||
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
|
||||
engines: {node: '>=14.17'}
|
||||
hasBin: true
|
||||
|
||||
undici-types@6.21.0:
|
||||
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
|
||||
|
||||
snapshots:
|
||||
|
||||
'@biomejs/biome@2.6.8':
|
||||
optionalDependencies:
|
||||
'@biomejs/cli-android-arm64': 2.6.8
|
||||
'@biomejs/cli-android-x64': 2.6.8
|
||||
'@biomejs/cli-darwin-arm64': 2.6.8
|
||||
'@biomejs/cli-darwin-x64': 2.6.8
|
||||
'@biomejs/cli-linux-arm64': 2.6.8
|
||||
'@biomejs/cli-linux-arm64-musl': 2.6.8
|
||||
'@biomejs/cli-linux-x64': 2.6.8
|
||||
'@biomejs/cli-linux-x64-musl': 2.6.8
|
||||
'@biomejs/cli-win32-arm64': 2.6.8
|
||||
'@biomejs/cli-win32-x64': 2.6.8
|
||||
|
||||
'@biomejs/cli-android-arm64@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@biomejs/cli-android-x64@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@biomejs/cli-darwin-arm64@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@biomejs/cli-darwin-x64@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@biomejs/cli-linux-arm64-musl@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@biomejs/cli-linux-arm64@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@biomejs/cli-linux-x64-musl@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@biomejs/cli-linux-x64@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@biomejs/cli-win32-arm64@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@biomejs/cli-win32-x64@2.6.8':
|
||||
optional: true
|
||||
|
||||
'@types/node@22.20.5':
|
||||
dependencies:
|
||||
undici-types: 6.21.0
|
||||
|
||||
typescript@5.9.3: {}
|
||||
|
||||
undici-types@6.21.0: {}
|
||||
43
src/i18n/en.ts
Normal file
43
src/i18n/en.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import type { Messages } from "./types.js";
|
||||
|
||||
export const en: Messages = {
|
||||
title: "Shift schedule templates for installers",
|
||||
tagline:
|
||||
"Build a monthly shift schedule for a crew of installers in a few minutes: pick a template, add people and a start date.",
|
||||
statusNote:
|
||||
"For now this is the product page. Screens for working with schedules will appear as tasks are completed.",
|
||||
whatTitle: "What it is",
|
||||
whatText:
|
||||
"The service lays out shifts and days off on the calendar from a ready-made template (5/2, 2/2, 1/3 or your own), highlights understaffed days and rest violations. You can adjust the finished schedule by hand, print it or export it to a spreadsheet.",
|
||||
forWhomTitle: "Who it is for",
|
||||
forWhom: [
|
||||
"Crew leader or dispatcher — builds the schedule and assigns replacements.",
|
||||
"Installer — sees their working days and days off.",
|
||||
"Area manager — sees the schedules of several crews.",
|
||||
],
|
||||
howToUseTitle: "How to use it",
|
||||
howToUse: [
|
||||
"Create a crew and add installers to it.",
|
||||
"Choose a schedule template, a month and a start date — the service builds the monthly schedule.",
|
||||
"Mark vacations and sick leave — the service shows the days that are short of people.",
|
||||
"Adjust the schedule by hand, print it or export it to a spreadsheet.",
|
||||
],
|
||||
howToCheckTitle: "How to check it",
|
||||
howToCheck: [
|
||||
"This page is the version for review: it updates after every accepted task.",
|
||||
"Look at the example below: the 2/2 template for a crew of four.",
|
||||
"Check that exactly two people work every day — see the «Working» row at the bottom of the example.",
|
||||
],
|
||||
exampleTitle: "Example: the 2/2 template for a crew of four",
|
||||
exampleCaption:
|
||||
"Rotation: the second pair starts the template two days later, so two people work every day.",
|
||||
personColumn: "Installer",
|
||||
workShort: "W",
|
||||
offShort: "O",
|
||||
legend: "W — working day, O — day off.",
|
||||
workingCount: "Working",
|
||||
languageLabel: "Language",
|
||||
notFoundTitle: "Page not found",
|
||||
notFoundText: "There is no such page. Go to the home page.",
|
||||
backHome: "Home page",
|
||||
};
|
||||
15
src/i18n/index.ts
Normal file
15
src/i18n/index.ts
Normal file
@ -0,0 +1,15 @@
|
||||
import { en } from "./en.js";
|
||||
import { kk } from "./kk.js";
|
||||
import { ru } from "./ru.js";
|
||||
import type { Messages } from "./types.js";
|
||||
|
||||
export type Lang = "ru" | "kk" | "en";
|
||||
export const LANGS: Record<Lang, { name: string; messages: Messages }> = {
|
||||
ru: { name: "Русский", messages: ru },
|
||||
kk: { name: "Қазақша", messages: kk },
|
||||
en: { name: "English", messages: en },
|
||||
};
|
||||
|
||||
export function pickLang(value: string | null | undefined): Lang {
|
||||
return value === "kk" || value === "en" || value === "ru" ? value : "ru";
|
||||
}
|
||||
43
src/i18n/kk.ts
Normal file
43
src/i18n/kk.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import type { Messages } from "./types.js";
|
||||
|
||||
export const kk: Messages = {
|
||||
title: "Инсталляторларға арналған үлгілік ауысым кестесі",
|
||||
tagline:
|
||||
"Инсталляторлар бригадасына бір айлық ауысым кестесін бірнеше минутта жасаңыз: үлгіні таңдаңыз, адамдарды және басталу күнін көрсетіңіз.",
|
||||
statusNote:
|
||||
"Қазір мұнда өнім беті. Кестемен жұмыс істеуге арналған беттер тапсырмалар орындалған сайын пайда болады.",
|
||||
whatTitle: "Бұл не",
|
||||
whatText:
|
||||
"Сервис ауысымдар мен демалыс күндерін дайын үлгі бойынша (5/2, 2/2, 1/3 немесе өз үлгіңіз) күнтізбеге орналастырады, адам жетіспеушілігін және демалыс ережелерінің бұзылуын көрсетеді. Дайын кестені қолмен түзетуге, басып шығаруға немесе кестеге жүктеуге болады.",
|
||||
forWhomTitle: "Кімге арналған",
|
||||
forWhom: [
|
||||
"Бригада басшысы немесе диспетчер — кестені жасайды және ауыстыруларды енгізеді.",
|
||||
"Инсталлятор — қашан жұмыс істейтінін және қашан демалатынын көреді.",
|
||||
"Учаске басшысы — бірнеше бригаданың кестелерін көреді.",
|
||||
],
|
||||
howToUseTitle: "Қалай пайдалану керек",
|
||||
howToUse: [
|
||||
"Бригада құрып, оған инсталляторларды қосыңыз.",
|
||||
"Кесте үлгісін, айды және басталу күнін таңдаңыз — сервис бір айлық кесте жасайды.",
|
||||
"Демалыстар мен науқас күндерін белгілеңіз — сервис адам жетпейтін күндерді көрсетеді.",
|
||||
"Кестені қолмен түзетіңіз, басып шығарыңыз немесе кестеге жүктеңіз.",
|
||||
],
|
||||
howToCheckTitle: "Қалай тексеру керек",
|
||||
howToCheck: [
|
||||
"Бұл бет — тексеруге арналған нұсқа: ол әр қабылданған тапсырмадан кейін жаңарады.",
|
||||
"Төмендегі мысалды қараңыз: бұл төрт адамнан тұратын бригадаға арналған 2/2 үлгісі.",
|
||||
"Айдың әр күнінде дәл екі адам жұмыс істейтінін тексеріңіз — мысалдың төменгі «Жұмыс істейді» жолын қараңыз.",
|
||||
],
|
||||
exampleTitle: "Мысал: төрт адамдық бригадаға арналған 2/2 үлгісі",
|
||||
exampleCaption:
|
||||
"Ротация: екінші жұптың үлгі басталуы екі күнге жылжытылған, сондықтан күн сайын екі адам жұмыс істейді.",
|
||||
personColumn: "Инсталлятор",
|
||||
workShort: "Ж",
|
||||
offShort: "Д",
|
||||
legend: "Ж — жұмыс күні, Д — демалыс күні.",
|
||||
workingCount: "Жұмыс істейді",
|
||||
languageLabel: "Тіл",
|
||||
notFoundTitle: "Бет табылмады",
|
||||
notFoundText: "Мұндай бет жоқ. Басты бетке өтіңіз.",
|
||||
backHome: "Басты бетке",
|
||||
};
|
||||
43
src/i18n/ru.ts
Normal file
43
src/i18n/ru.ts
Normal file
@ -0,0 +1,43 @@
|
||||
import type { Messages } from "./types.js";
|
||||
|
||||
export const ru: Messages = {
|
||||
title: "Шаблонный график сменности для инсталляторов",
|
||||
tagline:
|
||||
"Составьте график смен для бригады инсталляторов на месяц за несколько минут: выберите шаблон, укажите людей и дату начала.",
|
||||
statusNote:
|
||||
"Сейчас здесь страница продукта. Экраны для работы с графиком появятся по мере выполнения задач.",
|
||||
whatTitle: "Что это",
|
||||
whatText:
|
||||
"Сервис раскладывает смены и выходные по календарю по готовому шаблону (5/2, 2/2, 1/3 или ваш собственный), подсвечивает нехватку людей и нарушения отдыха. Готовый график можно поправить вручную, распечатать или выгрузить в таблицу.",
|
||||
forWhomTitle: "Для кого",
|
||||
forWhom: [
|
||||
"Руководитель бригады или диспетчер — составляет график и вносит замены.",
|
||||
"Инсталлятор — смотрит, когда работает и когда выходной.",
|
||||
"Руководитель участка — видит графики нескольких бригад.",
|
||||
],
|
||||
howToUseTitle: "Как пользоваться",
|
||||
howToUse: [
|
||||
"Создайте бригаду и добавьте в неё инсталляторов.",
|
||||
"Выберите шаблон графика, месяц и дату начала — сервис составит график на месяц.",
|
||||
"Отметьте отпуска и больничные — сервис покажет дни, где не хватает людей.",
|
||||
"Поправьте график вручную, распечатайте его или выгрузите в таблицу.",
|
||||
],
|
||||
howToCheckTitle: "Как проверить",
|
||||
howToCheck: [
|
||||
"Эта страница — версия для проверки: она обновляется после каждой принятой задачи.",
|
||||
"Посмотрите пример ниже: это шаблон 2/2 для бригады из четырёх человек.",
|
||||
"Проверьте, что в каждый день месяца работают ровно двое — смотрите строку «Работают» внизу примера.",
|
||||
],
|
||||
exampleTitle: "Пример: шаблон 2/2 для бригады из четырёх человек",
|
||||
exampleCaption:
|
||||
"Ротация: у второй пары начало шаблона сдвинуто на два дня, поэтому каждый день работают двое.",
|
||||
personColumn: "Инсталлятор",
|
||||
workShort: "Р",
|
||||
offShort: "В",
|
||||
legend: "Р — рабочий день, В — выходной.",
|
||||
workingCount: "Работают",
|
||||
languageLabel: "Язык",
|
||||
notFoundTitle: "Страница не найдена",
|
||||
notFoundText: "Такой страницы нет. Перейдите на главную страницу.",
|
||||
backHome: "На главную",
|
||||
};
|
||||
24
src/i18n/types.ts
Normal file
24
src/i18n/types.ts
Normal file
@ -0,0 +1,24 @@
|
||||
export interface Messages {
|
||||
title: string;
|
||||
tagline: string;
|
||||
statusNote: string;
|
||||
whatTitle: string;
|
||||
whatText: string;
|
||||
forWhomTitle: string;
|
||||
forWhom: string[];
|
||||
howToUseTitle: string;
|
||||
howToUse: string[];
|
||||
howToCheckTitle: string;
|
||||
howToCheck: string[];
|
||||
exampleTitle: string;
|
||||
exampleCaption: string;
|
||||
personColumn: string;
|
||||
workShort: string;
|
||||
offShort: string;
|
||||
legend: string;
|
||||
workingCount: string;
|
||||
languageLabel: string;
|
||||
notFoundTitle: string;
|
||||
notFoundText: string;
|
||||
backHome: string;
|
||||
}
|
||||
14
src/index.ts
Normal file
14
src/index.ts
Normal file
@ -0,0 +1,14 @@
|
||||
import { createAppServer } from "./server.js";
|
||||
|
||||
const port = Number(process.env.PORT ?? 3000);
|
||||
const server = createAppServer();
|
||||
server.listen(port, "0.0.0.0", () => {
|
||||
console.log(`listening on :${port}`);
|
||||
});
|
||||
|
||||
for (const signal of ["SIGTERM", "SIGINT"] as const) {
|
||||
process.on(signal, () => {
|
||||
server.close(() => process.exit(0));
|
||||
setTimeout(() => process.exit(0), 5000).unref();
|
||||
});
|
||||
}
|
||||
125
src/page.ts
Normal file
125
src/page.ts
Normal file
@ -0,0 +1,125 @@
|
||||
import { LANGS, type Lang } from "./i18n/index.js";
|
||||
import { buildRotation, TEMPLATE_2_2 } from "./schedule.js";
|
||||
|
||||
export const EXAMPLE_CREW = ["Айдос", "Марат", "Ержан", "Дмитрий"];
|
||||
const EXAMPLE_DAYS = 8;
|
||||
|
||||
export function escapeHtml(text: string): string {
|
||||
return text
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
}
|
||||
|
||||
const STYLE = `
|
||||
body{font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;margin:0;color:#1f2933;background:#f7f8fa;line-height:1.5}
|
||||
main{max-width:860px;margin:0 auto;padding:24px 20px 48px}
|
||||
header nav{display:flex;gap:12px;justify-content:flex-end;font-size:14px}
|
||||
h1{font-size:28px;margin:16px 0 8px}
|
||||
h2{font-size:20px;margin:28px 0 8px}
|
||||
.note{background:#fff8e1;border-left:4px solid #f5b700;padding:10px 14px}
|
||||
section{background:#fff;border-radius:8px;padding:4px 20px 16px;margin-top:16px;box-shadow:0 1px 2px rgba(0,0,0,.06)}
|
||||
table{border-collapse:collapse;margin-top:8px}
|
||||
th,td{border:1px solid #d9dee5;padding:6px 10px;text-align:center}
|
||||
th:first-child,td:first-child{text-align:left}
|
||||
td.work{background:#dff3e4}
|
||||
td.off{color:#7b8794}
|
||||
tfoot td{font-weight:600}
|
||||
a{color:#0b63c5}
|
||||
`;
|
||||
|
||||
function layout(lang: Lang, title: string, body: string): string {
|
||||
const nav = (Object.keys(LANGS) as Lang[])
|
||||
.map((code) =>
|
||||
code === lang
|
||||
? `<strong>${escapeHtml(LANGS[code].name)}</strong>`
|
||||
: `<a href="/?lang=${code}" hreflang="${code}">${escapeHtml(LANGS[code].name)}</a>`,
|
||||
)
|
||||
.join("");
|
||||
const m = LANGS[lang].messages;
|
||||
return `<!doctype html>
|
||||
<html lang="${lang}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${escapeHtml(title)}</title>
|
||||
<style>${STYLE}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header><nav aria-label="${escapeHtml(m.languageLabel)}">${nav}</nav></header>
|
||||
${body}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
function list(items: string[], ordered = false): string {
|
||||
const tag = ordered ? "ol" : "ul";
|
||||
return `<${tag}>${items.map((i) => `<li>${escapeHtml(i)}</li>`).join("")}</${tag}>`;
|
||||
}
|
||||
|
||||
function exampleTable(lang: Lang): string {
|
||||
const m = LANGS[lang].messages;
|
||||
const rows = buildRotation(TEMPLATE_2_2, EXAMPLE_CREW, EXAMPLE_DAYS);
|
||||
const dayNumbers = Array.from({ length: EXAMPLE_DAYS }, (_, d) => d + 1);
|
||||
const head = `<tr><th>${escapeHtml(m.personColumn)}</th>${dayNumbers.map((d) => `<th>${d}</th>`).join("")}</tr>`;
|
||||
const body = rows
|
||||
.map(
|
||||
(r) =>
|
||||
`<tr><td>${escapeHtml(r.person)}</td>${r.days
|
||||
.map(
|
||||
(d) => `<td class="${d}">${escapeHtml(d === "work" ? m.workShort : m.offShort)}</td>`,
|
||||
)
|
||||
.join("")}</tr>`,
|
||||
)
|
||||
.join("\n");
|
||||
const counts = dayNumbers.map((d) => rows.filter((r) => r.days[d - 1] === "work").length);
|
||||
const foot = `<tr><td>${escapeHtml(m.workingCount)}</td>${counts.map((c) => `<td>${c}</td>`).join("")}</tr>`;
|
||||
return `<table>
|
||||
<thead>${head}</thead>
|
||||
<tbody>
|
||||
${body}
|
||||
</tbody>
|
||||
<tfoot>${foot}</tfoot>
|
||||
</table>`;
|
||||
}
|
||||
|
||||
export function renderHome(lang: Lang): string {
|
||||
const m = LANGS[lang].messages;
|
||||
const body = `<h1>${escapeHtml(m.title)}</h1>
|
||||
<p>${escapeHtml(m.tagline)}</p>
|
||||
<p class="note">${escapeHtml(m.statusNote)}</p>
|
||||
<section>
|
||||
<h2>${escapeHtml(m.whatTitle)}</h2>
|
||||
<p>${escapeHtml(m.whatText)}</p>
|
||||
<h2>${escapeHtml(m.forWhomTitle)}</h2>
|
||||
${list(m.forWhom)}
|
||||
</section>
|
||||
<section>
|
||||
<h2>${escapeHtml(m.howToUseTitle)}</h2>
|
||||
${list(m.howToUse, true)}
|
||||
</section>
|
||||
<section>
|
||||
<h2>${escapeHtml(m.howToCheckTitle)}</h2>
|
||||
${list(m.howToCheck, true)}
|
||||
</section>
|
||||
<section id="example">
|
||||
<h2>${escapeHtml(m.exampleTitle)}</h2>
|
||||
<p>${escapeHtml(m.exampleCaption)}</p>
|
||||
${exampleTable(lang)}
|
||||
<p>${escapeHtml(m.legend)}</p>
|
||||
</section>`;
|
||||
return layout(lang, m.title, body);
|
||||
}
|
||||
|
||||
export function renderNotFound(lang: Lang): string {
|
||||
const m = LANGS[lang].messages;
|
||||
const body = `<h1>${escapeHtml(m.notFoundTitle)}</h1>
|
||||
<p>${escapeHtml(m.notFoundText)}</p>
|
||||
<p><a href="/?lang=${lang}">${escapeHtml(m.backHome)}</a></p>`;
|
||||
return layout(lang, m.notFoundTitle, body);
|
||||
}
|
||||
38
src/schedule.ts
Normal file
38
src/schedule.ts
Normal file
@ -0,0 +1,38 @@
|
||||
/** Один день шаблона графика: рабочий день или выходной. */
|
||||
export type DayKind = "work" | "off";
|
||||
|
||||
export interface PersonRow {
|
||||
person: string;
|
||||
days: DayKind[];
|
||||
}
|
||||
|
||||
export class EmptyTemplateError extends Error {
|
||||
constructor() {
|
||||
super("шаблон пуст");
|
||||
this.name = "EmptyTemplateError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Раскладывает шаблон графика по дням для списка людей (ротация).
|
||||
* Люди по порядку делятся на группы; число групп = длина шаблона / число рабочих дней
|
||||
* (округлённо, не меньше 1). Начало шаблона у группы g сдвинуто на round(g * длина / групп) дней.
|
||||
*/
|
||||
export function buildRotation(template: DayKind[], people: string[], days: number): PersonRow[] {
|
||||
const length = template.length;
|
||||
if (length === 0) throw new EmptyTemplateError();
|
||||
const workDays = template.filter((d) => d === "work").length;
|
||||
const groups = Math.max(1, Math.min(people.length, Math.round(length / Math.max(1, workDays))));
|
||||
return people.map((person, i) => {
|
||||
const group = Math.floor((i * groups) / people.length);
|
||||
const shift = Math.round((group * length) / groups);
|
||||
const row: DayKind[] = [];
|
||||
for (let d = 0; d < days; d++) {
|
||||
row.push(template[(((d - shift) % length) + length) % length] as DayKind);
|
||||
}
|
||||
return { person, days: row };
|
||||
});
|
||||
}
|
||||
|
||||
/** Шаблон 2/2: два рабочих дня, два выходных. */
|
||||
export const TEMPLATE_2_2: DayKind[] = ["work", "work", "off", "off"];
|
||||
30
src/server.ts
Normal file
30
src/server.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { pickLang } from "./i18n/index.js";
|
||||
import { renderHome, renderNotFound } from "./page.js";
|
||||
|
||||
const HTML = "text/html; charset=utf-8";
|
||||
|
||||
export function createAppServer(): Server {
|
||||
return createServer((req, res) => {
|
||||
const url = new URL(req.url ?? "/", "http://localhost");
|
||||
const method = req.method ?? "GET";
|
||||
if (method !== "GET" && method !== "HEAD") {
|
||||
res.writeHead(405, { Allow: "GET, HEAD", "Content-Type": "text/plain; charset=utf-8" });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
if (url.pathname === "/healthz") {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "text/plain; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
});
|
||||
res.end(method === "HEAD" ? undefined : "ok");
|
||||
return;
|
||||
}
|
||||
const lang = pickLang(url.searchParams.get("lang"));
|
||||
const found = url.pathname === "/";
|
||||
const html = found ? renderHome(lang) : renderNotFound(lang);
|
||||
res.writeHead(found ? 200 : 404, { "Content-Type": HTML });
|
||||
res.end(method === "HEAD" ? undefined : html);
|
||||
});
|
||||
}
|
||||
28
test/schedule.test.ts
Normal file
28
test/schedule.test.ts
Normal file
@ -0,0 +1,28 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { buildRotation, EmptyTemplateError, TEMPLATE_2_2 } from "../src/schedule.js";
|
||||
|
||||
const crew = ["Айдос", "Марат", "Ержан", "Дмитрий"];
|
||||
|
||||
describe("Requirement: Расчёт ротации шаблона", () => {
|
||||
it("Scenario: Шаблон 2/2 на четверых", () => {
|
||||
const rows = buildRotation(TEMPLATE_2_2, crew, 8);
|
||||
const erzhan = rows.find((r) => r.person === "Ержан");
|
||||
assert.deepEqual(erzhan?.days.slice(0, 4), ["off", "off", "work", "work"]);
|
||||
for (let d = 0; d < 8; d++) {
|
||||
assert.equal(rows.filter((r) => r.days[d] === "work").length, 2, `день ${d + 1}`);
|
||||
}
|
||||
});
|
||||
|
||||
it("Scenario: Пустой шаблон", () => {
|
||||
assert.throws(() => buildRotation([], crew, 8), EmptyTemplateError);
|
||||
assert.throws(() => buildRotation([], crew, 8), /шаблон пуст/);
|
||||
});
|
||||
|
||||
it("1/3 на четверых: каждый день работает один", () => {
|
||||
const rows = buildRotation(["work", "off", "off", "off"], crew, 8);
|
||||
for (let d = 0; d < 8; d++) {
|
||||
assert.equal(rows.filter((r) => r.days[d] === "work").length, 1);
|
||||
}
|
||||
});
|
||||
});
|
||||
63
test/server.test.ts
Normal file
63
test/server.test.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import assert from "node:assert/strict";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { after, before, describe, it } from "node:test";
|
||||
import { LANGS } from "../src/i18n/index.js";
|
||||
import { createAppServer } from "../src/server.js";
|
||||
|
||||
const server = createAppServer();
|
||||
let base = "";
|
||||
|
||||
before(async () => {
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
after(() => server.close());
|
||||
|
||||
describe("Requirement: Проверка здоровья", () => {
|
||||
it("Scenario: Сервис здоров", async () => {
|
||||
const res = await fetch(`${base}/healthz`);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(await res.text(), "ok");
|
||||
});
|
||||
|
||||
it("Scenario: Неизвестный адрес", async () => {
|
||||
const res = await fetch(`${base}/nope`);
|
||||
assert.equal(res.status, 404);
|
||||
const html = await res.text();
|
||||
assert.match(html, /Страница не найдена/);
|
||||
assert.match(html, /href="\/\?lang=ru"/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Requirement: Страница продукта", () => {
|
||||
it("Scenario: Открыть страницу продукта", async () => {
|
||||
const res = await fetch(`${base}/`);
|
||||
assert.equal(res.status, 200);
|
||||
assert.match(res.headers.get("content-type") ?? "", /text\/html/);
|
||||
const html = await res.text();
|
||||
assert.match(html, /<html lang="ru">/);
|
||||
assert.match(html, /<h2>Как пользоваться<\/h2>/);
|
||||
assert.match(html, /<h2>Как проверить<\/h2>/);
|
||||
const row = html.split("\n").find((l) => l.includes("<td>Айдос</td>")) ?? "";
|
||||
const cells = [...row.matchAll(/<td class="\w+">(.)<\/td>/g)].map((m) => m[1]);
|
||||
assert.deepEqual(cells.slice(0, 4), ["Р", "Р", "В", "В"]);
|
||||
});
|
||||
|
||||
for (const [lang, htmlLang] of [
|
||||
["ru", "ru"],
|
||||
["kk", "kk"],
|
||||
["en", "en"],
|
||||
["de", "ru"],
|
||||
]) {
|
||||
it(`Scenario Outline: Язык страницы — lang=${lang}`, async () => {
|
||||
const html = await (await fetch(`${base}/?lang=${lang}`)).text();
|
||||
assert.match(html, new RegExp(`<html lang="${htmlLang}">`));
|
||||
});
|
||||
}
|
||||
|
||||
it("во всех языках одинаковый набор текстов", () => {
|
||||
const keys = (lang: keyof typeof LANGS) => Object.keys(LANGS[lang].messages).sort();
|
||||
assert.deepEqual(keys("kk"), keys("ru"));
|
||||
assert.deepEqual(keys("en"), keys("ru"));
|
||||
});
|
||||
});
|
||||
5
tsconfig.build.json
Normal file
5
tsconfig.build.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": { "rootDir": "src", "outDir": "dist" },
|
||||
"include": ["src"]
|
||||
}
|
||||
15
tsconfig.json
Normal file
15
tsconfig.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"types": ["node"],
|
||||
"outDir": "dist",
|
||||
"rootDir": "."
|
||||
},
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
5
tsconfig.test.json
Normal file
5
tsconfig.test.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": { "rootDir": ".", "outDir": "dist-test" },
|
||||
"include": ["src", "test"]
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user