feat: Phase 6+9 real-time уведомления, CSS Modules, UI-правки

This commit is contained in:
Suslov-MD
2026-08-16 15:28:21 +00:00
parent 476250d5e3
commit 65c44f570c
31 changed files with 1506 additions and 605 deletions
+188 -123
View File
@@ -1,84 +1,88 @@
# News Editor # News Editor
Full-stack application for creating, editing, and publishing news articles. Full-stack приложение для создания, редактирования и публикации новостей. Markdown-редактор, real-time уведомления, отложенная публикация.
## Architecture ## Архитектура
``` ```
┌──────────────────────────────────┐ ┌──────────────────────────────────────────┐
│ Nginx (client) │ │ Nginx (client) │
│ React SPA + reverse proxy │ │ React SPA + reverse proxy │
│ /api → server, /socket.io → ws │ │ /api → server, /socket.io → ws, │
└────────────────┬─────────────────┘ │ /uploads → server │
│ └────────────────────┬─────────────────────┘
▼ │
┌──────────────────────────────────┐ ▼
│ Express Backend │ ┌──────────────────────────────────────────┐
│ Auth (JWT), News CRUD, │ │ Express Backend │
│ Upload (multer), Scheduler, │ │ Auth (JWT), News CRUD, Upload (multer), │
│ Socket.IO (Phase 6) │ │ Scheduler, Socket.IO, Notifications │
└────────────────┬─────────────────┘ └────────────────────┬─────────────────────┘
│ │
▼ ▼
┌──────────────────────────────────┐ ┌──────────────────────────────────────────┐
│ MongoDB │ │ MongoDB │
│ users, news, notifications │ │ users, news, notifications │
└──────────────────────────────────┘ └──────────────────────────────────────────┘
``` ```
## Tech Stack ## Стек технологий
| Layer | Technology | | Слой | Технология |
|-----------|---------------------------------------------| |-------------|-----------------------------------------------------|
| Backend | Node.js 22, Express, TypeScript, Mongoose | | Бэкенд | Node.js 22, Express, TypeScript (strict) |
| Auth | JWT (jsonwebtoken), bcrypt (cost 12) | | Авторизация | JWT (jsonwebtoken), bcrypt (cost 12) |
| Real-time | Socket.IO (Phase 6) | | Real-time | Socket.IO (JWT auth, user rooms) |
| Upload | multer (disk storage, UUID filenames) | | Файлы | multer (disk storage, UUID filenames, MIME whitelist) |
| Frontend | React 18, TypeScript, Vite, react-router-dom | | Фронтенд | React 18, TypeScript, Vite, react-router-dom |
| Editor | Markdown (react-markdown, remark-gfm) | | Стили | SCSS Modules (per-component) + global base |
| Tests | Vitest, Supertest, mongodb-memory-server | | Редактор | Markdown (react-markdown, remark-gfm, rehype-sanitize) |
| Deploy | Docker Compose (nginx + node + mongo) | | Тесты | Vitest, Supertest, mongodb-memory-server |
| Деплой | Docker Compose (nginx + node + mongo) |
## Project Structure ## Структура проекта
``` ```
news-editor/ news-editor/
├── package.json ← root scripts (dev, test, lint, build) ├── package.json ← root scripts (dev, test, lint, build)
├── docker-compose.yml ← production stack ├── docker-compose.yml ← production-стек
├── .env ← docker env vars (JWT_SECRET, PORT) ├── .env ← env для docker (JWT_SECRET, PORT)
├── server/ ├── server/
│ ├── Dockerfile ← multi-stage: tsc → node:22-alpine │ ├── Dockerfile ← multi-stage: tsc → node:22-alpine
│ ├── src/ │ ├── src/
│ │ ├── app.ts ← Express app factory │ │ ├── app.ts ← фабрика Express-приложения
│ │ ├── server.ts ← entry point (HTTP + scheduler) │ │ ├── server.ts ← точка входа (HTTP + Socket.IO + scheduler)
│ │ ├── config/ ← env, database │ │ ├── config/ ← env, database
│ │ ├── middleware/ ← auth (JWT), error, notFound, upload (multer) │ │ ├── middleware/ ← auth (JWT), error, notFound, upload (multer)
│ │ ├── models/ ← User, News (Mongoose) │ │ ├── models/ ← User, News, Notification (Mongoose)
│ │ ├── routes/ ← auth, news, upload, health │ │ ├── routes/ ← auth, news, notification, upload, health
│ │ ├── services/ ← publicationScheduler │ │ ├── services/ ← publicationScheduler, notification
│ │ ├── socket/ ← Socket.IO server + типизация
│ │ └── utils/ ← ApiError, asyncHandler, jwt │ │ └── utils/ ← ApiError, asyncHandler, jwt
│ └── tests/ ← integration tests (Vitest + Supertest) │ └── tests/ ← интеграционные тесты (Vitest + Supertest)
└── client/ └── client/
├── Dockerfile ← multi-stage: vite build → nginx:alpine ├── Dockerfile ← multi-stage: vite build → nginx:alpine
├── nginx.conf ← SPA + proxy ├── nginx.conf ← SPA + proxy
└── src/ └── src/
├── api/ ← fetch client (apiFetch, apiUpload) ├── api/ ← fetch клиент (apiFetch, apiUpload), типы
├── auth/ ← AuthContext (login, register, logout) ├── auth/ ← AuthContext (login, register, logout)
├── components/ ← ProtectedRoute ├── components/ ← ProtectedRoute, NotificationBell, MarkdownToolbar
├── pages/ ← Login, Register, Home ├── hooks/ ← useNewsEditor, useNotifications, useSocket
├── pages/ ← Login, Register, Home, NewsList, NewsEditor
├── styles/ ← global.scss (base reset + shared)
└── App.tsx ← BrowserRouter + Routes └── App.tsx ← BrowserRouter + Routes
``` ```
## Prerequisites ## Требования
- Node.js >= 20 - Node.js >= 20
- npm >= 10 - npm >= 10
- MongoDB (local, Atlas, or Docker) - MongoDB (локальная, Atlas, или Docker)
- Docker + Docker Compose (for production deploy) - Docker + Docker Compose (для production-деплоя)
## Development Setup ## Разработка
### 1. Install dependencies ### 1. Установка зависимостей
```bash ```bash
npm install npm install
@@ -86,13 +90,13 @@ npm --prefix server install
npm --prefix client install npm --prefix client install
``` ```
### 2. Configure environment ### 2. Конфигурация окружения
```bash ```bash
cp server/.env.example server/.env cp server/.env.example server/.env
``` ```
Edit `server/.env`: Редактируем `server/.env`:
```env ```env
NODE_ENV=development NODE_ENV=development
@@ -105,43 +109,43 @@ MAX_UPLOAD_SIZE=20971520
SCHEDULER_INTERVAL_MS=20000 SCHEDULER_INTERVAL_MS=20000
``` ```
### 3. Run MongoDB (if not already running) ### 3. Запуск MongoDB (если не запущена)
```bash ```bash
# Option A: Docker # Вариант A: Docker
docker run -d --name mongo -p 27017:27017 mongo:7 docker run -d --name mongo -p 27017:27017 mongo:7
# Option B: Local install # Вариант B: Локальная установка
mongod --dbpath ~/mongodb-data mongod --dbpath ~/mongodb-data
``` ```
### 4. Run ### 4. Запуск
```bash ```bash
# Both server + client (uses concurrently) # Сервер + клиент одновременно (concurrently)
npm run dev npm run dev
# Or separately # Или по отдельности
npm --prefix server run dev # http://localhost:3000 npm --prefix server run dev # http://localhost:3000
npm --prefix client run dev # http://localhost:5173 npm --prefix client run dev # http://localhost:5173
``` ```
- Backend: http://localhost:3000 - Бэкенд: http://localhost:3000
- Frontend: http://localhost:5173 - Фронтенд: http://localhost:5173
- LAN: http://192.168.50.7:5173 - LAN: http://192.168.50.7:5173
- Health: http://localhost:3000/api/health - Health: http://localhost:3000/api/health
## Production (Docker Compose) ## Production (Docker Compose)
Полный production-стек одним `docker compose up`. Полный production-стек одной командой `docker compose up`.
### Архитектура ### Архитектура
| Сервис | Образ | Описание | | Сервис | Образ | Описание |
|--------|-------|----------| |----------|--------------------------------|-----------------------------------|
| `mongo` | mongo:7 | MongoDB с healthcheck | | `mongo` | mongo:7 | MongoDB с healthcheck |
| `server` | multi-stage (node:22-alpine) | Express API + Socket.IO | | `server` | multi-stage (node:22-alpine) | Express API + Socket.IO |
| `client` | multi-stage (nginx:alpine) | React SPA + reverse proxy | | `client` | multi-stage (nginx:alpine) | React SPA + reverse proxy |
### Запуск ### Запуск
@@ -162,10 +166,10 @@ curl http://localhost:8080/api/health
### Переменные окружения (.env) ### Переменные окружения (.env)
| Переменная | По умолчанию | Описание | | Переменная | По умолчанию | Описание |
|------------|-------------|----------| |-----------------|----------------------|---------------------------------------------|
| `JWT_SECRET` | — (обязательна) | Секрет подписи JWT | | `JWT_SECRET` | — (обязательна) | Секрет подписи JWT |
| `PORT` | `8080` | Внешний порт nginx | | `PORT` | `8080` | Внешний порт nginx |
| `CLIENT_ORIGIN` | `http://localhost:8080` | CORS origin (через запятую — несколько) | | `CLIENT_ORIGIN` | `http://localhost:8080` | CORS origin (через запятую — несколько) |
### Остановка ### Остановка
@@ -180,68 +184,128 @@ docker compose down -v
### Файлы ### Файлы
| Файл | Назначение | | Файл | Назначение |
|------|------------| |-----------------------|-----------------------------------------------|
| `docker-compose.yml` | Оркестрация: mongo + server + client | | `docker-compose.yml` | Оркестрация: mongo + server + client |
| `server/Dockerfile` | Multi-stage: tsc build → node:22-alpine | | `server/Dockerfile` | Multi-stage: tsc build → node:22-alpine |
| `client/Dockerfile` | Multi-stage: vite build → nginx:alpine | | `client/Dockerfile` | Multi-stage: vite build → nginx:alpine |
| `client/nginx.conf` | SPA fallback + proxy /api, /uploads, /socket.io | | `client/nginx.conf` | SPA fallback + proxy /api, /uploads, /socket.io |
| `.dockerignore` | Исключения из build context | | `.dockerignore` | Исключения из build context |
## API Endpoints ## API
### Auth ### Авторизация
| Method | Path | Auth | Description | | Method | Path | Auth | Описание |
|--------|----------------------|------|--------------------------------| |--------|----------------------|------|---------------------------------------|
| POST | `/api/auth/register` | – | Register, returns `{token, user}` | | POST | `/api/auth/register` | – | Регистрация, возвращает `{token, user}` |
| POST | `/api/auth/login` | – | Login, returns `{token, user}` | | POST | `/api/auth/login` | – | Логин, возвращает `{token, user}` |
| GET | `/api/auth/me` | ✓ | Current user info | | GET | `/api/auth/me` | ✓ | Текущий пользователь |
### News (authenticated) ### Новости (авторизовано)
| Method | Path | Description | | Method | Path | Описание |
|--------|------------------------|------------------------------------| |--------|-------------------------|---------------------------------------|
| GET | `/api/news` | List own news | | GET | `/api/news` | Список своих новостей |
| GET | `/api/news/:id` | Get one news article | | GET | `/api/news/:id` | Одна новость |
| POST | `/api/news` | Create draft | | POST | `/api/news` | Создать черновик |
| PATCH | `/api/news/:id` | Update own article | | PATCH | `/api/news/:id` | Обновить свою новость |
| DELETE | `/api/news/:id` | Delete own article | | DELETE扭头 | `/api/news/:id` | Удалить свою новость |
| POST | `/api/news/:id/publish`| Publish immediately | | POST | `/api/news/:id/publish` | Опубликовать немедленно |
| POST | `/api/news/:id/schedule`| Schedule publication (`{scheduledAt}`) | | POST | `/api/news/:id/schedule`| Отложенная публикация (`{scheduledAt}`) |
### Upload ### Уведомления (авторизовано)
| Method | Path | Auth | Description | | Method | Path | Описание |
|--------|---------------|------|------------------------------------------| |--------|-----------------------------------|-----------------------------|
| POST | `/api/uploads`| ✓ | Upload file (multipart), returns `{file}` | | GET | `/api/notifications` | Список (последние 50) |
| GET | `/uploads/:filename` | – | Serve uploaded file (static) | | GET | `/api/notifications/unread-count` | Счётчик непрочитанных |
| PATCH | `/api/notifications/:id/read` | Прочитать одно |
| POST | `/api/notifications/read-all` | Прочитать все |
### Загрузка файлов
| Method | Path | Auth | Описание |
|--------|----------------------|------|-------------------------------------------|
| POST | `/api/uploads` | ✓ | Загрузить файл (multipart) |
| GET | `/uploads/:filename` | – | Статическая раздача загруженного файла |
**MIME whitelist**: image/jpeg, image/png, image/gif, image/webp, application/pdf, application/msword, .docx **MIME whitelist**: image/jpeg, image/png, image/gif, image/webp, application/pdf, application/msword, .docx
### Health ### Health
| Method | Path | Description | | Method | Path | Описание |
|--------|----------------|-------------------| |--------|---------------|-------------------|
| GET | `/api/health` | `{"status":"ok"}` | | GET | `/api/health` | `{"status":"ok"}` |
## Scheduled Publication ## Real-time уведомления (Socket.IO)
The backend runs a poller every 20 seconds (configurable via `SCHEDULER_INTERVAL_MS`) that finds articles with: Socket.IO подключён к тому же HTTP-серверу, что и Express.
### Подключение клиента
```js
import { io } from 'socket.io-client';
const socket = io('http://localhost:8080', {
auth: { token: jwtToken },
transports: ['websocket', 'polling'],
});
// Real-time уведомления
socket.on('notification', (data) => {
console.log(data.title, data.message);
});
```
### Аутентификация
JWT передаётся через `handshake.auth.token`. Сервер верифицирует токен в `io.use()` middleware и при неудаче отклоняет подключение.
### События
| Event | Payload | Когда |
|----------------|--------------------------------------------------|--------------------------------|
| `notification` | `{id, type, title, message, isRead, createdAt}` | news.deleted, published, scheduled |
### Rooms
Каждый подключённый socket добавляется в room `user:{userId}`. Уведомления отправляются через `io.to('user:{id}').emit(...)`.
## Отложенная публикация
Бэкенд запускает poller каждые 20 секунд (настраивается через `SCHEDULER_INTERVAL_MS`), который находит статьи:
```js ```js
{ status: 'scheduled', scheduledAt: { $lte: now } } { status: 'scheduled', scheduledAt: { $lte: now } }
``` ```
and atomically transitions them to `published` via `findOneAndUpdate`. Survives process restarts — no in-memory `setTimeout` per article. и атомарно переводит их в `published` через `findOneAndUpdate`. Выживает после перезапуска процесса — без in-memory `setTimeout` на статью.
## Upload ## Загрузка файлов
Files are stored on the filesystem (`UPLOAD_DIR`, default `server/uploads/`). Filenames are UUID-based to prevent collisions. Max size: 20 MB (configurable via `MAX_UPLOAD_SIZE`). Файлы хранятся на файловой системе (`UPLOAD_DIR`, по умолчанию `server/uploads/`). Имена файлов — UUID (защита от коллизий). Максимальный размер: 20 МБ (настраивается через `MAX_UPLOAD_SIZE`).
## Error Format ## Фронтенд: Markdown-редактор
All errors follow a consistent shape: - **Toolbar**: Bold, Italic, Heading, Quote, Code, Link, Image, File
- **Preview**: react-markdown + remark-gfm + rehype-sanitize
- **Upload**: изображение/файл → вставка markdown-ссылки в textarea
- **UI зависит от статуса**:
- Draft/scheduled: Сохранить + Опубликовать + Удалить + Schedule + toggle Редактор/Предпросмотр
- Published: Сохранить + Удалить (по умолчанию preview, нет publish/schedule)
## Фронтенд: Колокольчик уведомлений
- 🔔 иконка с badge (счётчик непрочитанных)
- Клик → панель со списком уведомлений
- Клик по уведомлению → пометить прочитанным
- "Прочитать все" → пометить все
- Real-time: новые уведомления появляются без перезагрузки (Socket.IO)
## Формат ошибок
Все ошибки имеют единый формат:
```json ```json
{ {
@@ -252,32 +316,33 @@ All errors follow a consistent shape:
} }
``` ```
## Testing ## Тесты
```bash ```bash
npm --prefix server test # Vitest + Supertest + mongodb-memory-server (46 tests) npm --prefix server test # Vitest + Supertest + mongodb-memory-server (46 тестов)
npm test # all tests npm test # все тесты
``` ```
## Lint ## Линт
```bash ```bash
npm run lint # ESLint (strictTypeChecked + sonarjs) for server + client npm run lint # ESLint (strictTypeChecked + sonarjs) для server + client
``` ```
## Production Build ## Production-сборка
```bash ```bash
npm --prefix client run build npm --prefix client run build
# Output: client/dist/ (static files, deployable to any static host) # Результат: client/dist/ (статические файлы, можно деплоить на любой хостинг)
``` ```
## Demo Flow ## Демонстрационный сценарий
1. Register → Login → see JWT with user `id` 1. Регистрация → Логин → JWT с `id` пользователя
2. Create a draft → add markdown content 2. Создать черновик → добавить markdown через toolbar
3. Upload an image → get URL → insert into article 3. Загрузить изображение → получить URL → вставить в статью
4. Save draft → see in list 4. Сохранить черновик → виден в списке (с preview контента)
5. Schedule publication for 1–2 min ahead → watch it auto-publish 5. Запланировать публикацию на 1–2 мин вперёд → наблюдать авто-публикацию
6. Publish immediately → article is live 6. Опубликовать немедленно → статья live (UI переключается в read-only preview)
7. Delete article 7. Колокольчик показывает real-time события
8. Удалить статью
+1 -4
View File
@@ -14,7 +14,7 @@
"react-router-dom": "^7.2.0", "react-router-dom": "^7.2.0",
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.0", "remark-gfm": "^4.0.0",
"socket.io-client": "^4.8.1" "socket.io-client": "^4.8.3"
}, },
"devDependencies": { "devDependencies": {
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1", "@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
@@ -1986,14 +1986,12 @@
"version": "15.7.15", "version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/react": { "node_modules/@types/react": {
"version": "18.3.31", "version": "18.3.31",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
"integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==", "integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@types/prop-types": "*", "@types/prop-types": "*",
@@ -3293,7 +3291,6 @@
"version": "3.2.3", "version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/damerau-levenshtein": { "node_modules/damerau-levenshtein": {
+1 -1
View File
@@ -16,7 +16,7 @@
"react-router-dom": "^7.2.0", "react-router-dom": "^7.2.0",
"rehype-sanitize": "^6.0.0", "rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.0", "remark-gfm": "^4.0.0",
"socket.io-client": "^4.8.1" "socket.io-client": "^4.8.3"
}, },
"devDependencies": { "devDependencies": {
"@eslint-community/eslint-plugin-eslint-comments": "^4.4.1", "@eslint-community/eslint-plugin-eslint-comments": "^4.4.1",
+15
View File
@@ -28,3 +28,18 @@ export interface NewsItem {
export interface UploadResponse { export interface UploadResponse {
file: { url: string; filename: string; size: number }; file: { url: string; filename: string; size: number };
} }
/** Тип уведомления. */
export type NotificationType = 'news.created' | 'news.updated' | 'news.deleted' | 'news.scheduled' | 'news.published';
/** Уведомление (сериализованное от backend). */
export interface NotificationItem {
id: string;
actor: string | null;
type: NotificationType;
news: string | null;
title: string;
message: string;
isRead: boolean;
createdAt: string;
}
+1 -1
View File
@@ -12,7 +12,7 @@ interface MarkdownToolbarProps {
*/ */
export function MarkdownToolbar({ onAction, onImageUpload, onFileUpload }: MarkdownToolbarProps) { export function MarkdownToolbar({ onAction, onImageUpload, onFileUpload }: MarkdownToolbarProps) {
return ( return (
<div className="markdown-toolbar" role="toolbar" aria-label="Форматирование"> <div role="toolbar" aria-label="Форматирование">
<button type="button" title="Полужирный" onClick={() => { onAction('bold'); }}> <button type="button" title="Полужирный" onClick={() => { onAction('bold'); }}>
<strong>B</strong> <strong>B</strong>
</button> </button>
@@ -0,0 +1,145 @@
.wrapper {
position: relative;
display: inline-block;
}
.trigger {
background: none;
border: none;
cursor: pointer;
padding: 0.35rem 0.5rem;
border-radius: 6px;
transition: background 0.15s;
&:hover {
background: #f3f4f6;
}
}
.bell {
position: relative;
display: inline-flex;
align-items: center;
font-size: 1.25rem;
}
.badge {
position: absolute;
top: -6px;
right: -10px;
background: #ef4444;
color: #fff;
font-size: 0.65rem;
font-weight: 700;
border-radius: 10px;
padding: 1px 5px;
min-width: 16px;
text-align: center;
line-height: 1.4;
}
.panel {
position: absolute;
top: calc(100% + 0.625rem);
right: 0;
width: 340px;
max-height: 420px;
overflow-y: auto;
background: #fff;
border: 1px solid #e5e7eb;
border-radius: 10px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
z-index: 100;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.875rem 1.25rem;
border-bottom: 1px solid #f3f4f6;
h3 {
margin: 0;
font-size: 0.9rem;
font-weight: 600;
}
}
.markAll {
background: none;
border: none;
color: #3b82f6;
cursor: pointer;
font-size: 0.8rem;
padding: 0;
&:hover {
text-decoration: underline;
}
}
.list {
list-style: none;
margin: 0;
padding: 0.5rem 0;
}
.item {
border-bottom: 1px solid #f9fafb;
&:last-child {
border-bottom: none;
}
&.unread {
background: #f0f7ff;
}
&.read {
opacity: 0.65;
}
}
.itemBtn {
display: block;
width: 100%;
padding: 0.75rem 1.25rem;
border: none;
background: none;
cursor: pointer;
text-align: left;
transition: background 0.1s;
&:hover {
background: #f9fafb;
}
}
.itemTitle {
display: block;
font-size: 0.85rem;
font-weight: 600;
color: #111827;
}
.itemMessage {
display: block;
font-size: 0.82rem;
color: #4b5563;
margin-top: 0.2rem;
}
.itemTime {
display: block;
font-size: 0.72rem;
color: #9ca3af;
margin-top: 0.35rem;
}
.empty {
padding: 2rem 1.25rem;
text-align: center;
color: #9ca3af;
font-size: 0.85rem;
}
+112
View File
@@ -0,0 +1,112 @@
import { useState } from 'react';
import { useNotifications } from '../hooks/useNotifications.js';
import styles from './NotificationBell.module.scss';
import type { NotificationItem } from '../api/types.js';
/**
* Форматирует дату в коротком формате.
*
* @param iso — ISO-дата
* @returns строка вида "16.08 12:30"
*/
function formatDateTime(iso: string): string {
const d = new Date(iso);
const day = String(d.getDate()).padStart(2, '0');
const month = String(d.getMonth() + 1).padStart(2, '0');
const hours = String(d.getHours()).padStart(2, '0');
const minutes = String(d.getMinutes()).padStart(2, '0');
return `${day}.${month} ${hours}:${minutes}`;
}
/**
* Одиночное уведомление в списке.
*/
function NotificationItemRow({
notification, onRead,
}: {
readonly notification: NotificationItem;
readonly onRead: (id: string) => void;
}) {
const cls = notification.isRead ? styles.read : styles.unread;
return (
<li className={`${styles.item} ${cls}`}>
<button
type="button"
className={styles.itemBtn}
onClick={() => { if (!notification.isRead) { onRead(notification.id); } }}
>
<span className={styles.itemTitle}>{notification.title}</span>
<span className={styles.itemMessage}>{notification.message}</span>
<span className={styles.itemTime}>{formatDateTime(notification.createdAt)}</span>
</button>
</li>
);
}
/**
* Компонент колокольчика уведомлений.
*
* Отображает иконку с badge, по клику раскрывает список уведомлений.
* Подключается к Socket.IO для real-time обновлений.
*/
export function NotificationBell({ token }: { readonly token: string | null }) {
const [open, setOpen] = useState(false);
const {
notifications, unreadCount, markAsRead, markAllAsRead,
} = useNotifications(token);
const handleMarkAsRead = (id: string): void => {
markAsRead(id).catch(() => { /* ignore */ });
};
const handleMarkAll = (): void => {
markAllAsRead().catch(() => { /* ignore */ });
};
if (token === null) {
return null;
}
return (
<div className={styles.wrapper}>
<button
type="button"
className={styles.trigger}
onClick={() => { setOpen((v) => !v); }}
aria-label="Уведомления"
>
<span className={styles.bell}>
🔔
{unreadCount > 0 && <span className={styles.badge}>{unreadCount > 99 ? '99+' : String(unreadCount)}</span>}
</span>
</button>
{open ? <div className={styles.panel}>
<div className={styles.header}>
<h3>Уведомления</h3>
{unreadCount > 0
? (
<button type="button" className={styles.markAll} onClick={handleMarkAll}>
Прочитать все
</button>
)
: null}
</div>
{notifications.length === 0
? <p className={styles.empty}>Нет уведомлений</p>
: (
<ul className={styles.list}>
{notifications.map((n) => (
<NotificationItemRow key={n.id} notification={n} onRead={handleMarkAsRead} />
))}
</ul>
)}
</div> : null}
</div>
);
}
+31 -6
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react'; import { useCallback, useEffect, useRef, useState, type ChangeEvent } from 'react';
import { apiFetch, apiUpload } from '../api/client.js'; import { apiFetch, apiUpload } from '../api/client.js';
@@ -10,6 +10,7 @@ import type { UploadResponse } from '../api/types.js';
function useLoadNews(newsId: string | undefined, isNew: boolean) { function useLoadNews(newsId: string | undefined, isNew: boolean) {
const [title, setTitle] = useState(''); const [title, setTitle] = useState('');
const [content, setContent] = useState(''); const [content, setContent] = useState('');
const [newsStatus, setNewsStatus] = useState<'draft' | 'scheduled' | 'published'>('draft');
const [loading, setLoading] = useState(!isNew); const [loading, setLoading] = useState(!isNew);
useEffect(() => { useEffect(() => {
@@ -20,9 +21,13 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
void (async () => { void (async () => {
try { try {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- newsId гарантированно string (проверено isNew) // eslint-disable-next-line @typescript-eslint/restrict-template-expressions -- newsId гарантированно string (проверено isNew)
const data = await apiFetch<{ news: { title: string; content: string } }>(`/news/${newsId}`); const data = await apiFetch<{ news: { title: string; content: string; status: string } }>(`/news/${newsId}`);
setTitle(data.news.title); setTitle(data.news.title);
setContent(data.news.content); setContent(data.news.content);
const s = data.news.status;
if (s === 'draft' || s === 'scheduled' || s === 'published') {
setNewsStatus(s);
}
} catch { } catch {
// Ошибка загрузки — остаёмся с пустым состоянием // Ошибка загрузки — остаёмся с пустым состоянием
} finally { } finally {
@@ -31,7 +36,7 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
})(); })();
}, [newsId, isNew]); }, [newsId, isNew]);
return { title, setTitle, content, setContent, loading }; return { title, setTitle, content, setContent, newsStatus, loading };
} }
/** /**
@@ -43,7 +48,7 @@ function useLoadNews(newsId: string | undefined, isNew: boolean) {
/* eslint-disable max-lines-per-function -- хук-оркестратор */ /* eslint-disable max-lines-per-function -- хук-оркестратор */
export function useNewsEditor(newsId: string | undefined) { export function useNewsEditor(newsId: string | undefined) {
const isNew = newsId === undefined; const isNew = newsId === undefined;
const { title, setTitle, content, setContent, loading } = useLoadNews(newsId, isNew); const { title, setTitle, content, setContent, newsStatus, loading } = useLoadNews(newsId, isNew);
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const [error, setError] = useState(''); const [error, setError] = useState('');
const [scheduleDate, setScheduleDate] = useState(''); const [scheduleDate, setScheduleDate] = useState('');
@@ -203,14 +208,34 @@ export function useNewsEditor(newsId: string | undefined) {
if (action === 'link') { insertMarkdown('[', '](https://)'); } if (action === 'link') { insertMarkdown('[', '](https://)'); }
}, [insertMarkdown]); }, [insertMarkdown]);
/** Обработчик file input для изображений. */
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input
e.target.value = '';
}, [handleFileUpload]);
/** Обработчик file input для файлов. */
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input
e.target.value = '';
}, [handleFileUpload]);
return { return {
isNew, title, setTitle, isNew, title, setTitle,
content, setContent, content, setContent, newsStatus,
loading, saving, error, loading, saving, error,
scheduleDate, setScheduleDate, scheduleDate, setScheduleDate,
textareaRef, textareaRef,
insertMarkdown, handleToolbarAction, insertMarkdown, handleToolbarAction,
handleFileUpload, handleFileUpload, onImageChange, onFileChange,
onSave, onPublish, onDelete, onSchedule, onSave, onPublish, onDelete, onSchedule,
}; };
} }
+89
View File
@@ -0,0 +1,89 @@
import { useCallback, useEffect, useState } from 'react';
import { apiFetch } from '../api/client.js';
import { useSocket } from './useSocket.js';
import type { NotificationItem } from '../api/types.js';
/**
* Хук для управления уведомлениями.
*
* Подписывается на Socket.IO события, загружает список уведомлений,
* предоставляет счётчик непрочитанных и методы отметки.
*
* @param token — JWT токен (null если не авторизован)
* @returns состояние и методы для NotificationBell
*/
export function useNotifications(token: string | null) {
const socket = useSocket(token);
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
const [unreadCount, setUnreadCount] = useState(0);
/** Загружает список уведомлений и счётчик непрочитанных. */
const fetchNotifications = useCallback(async (): Promise<void> => {
try {
const [listRes, countRes] = await Promise.all([
apiFetch<{ notifications: NotificationItem[] }>('/notifications'),
apiFetch<{ count: number }>('/notifications/unread-count'),
]);
setNotifications(listRes.notifications);
setUnreadCount(countRes.count);
} catch {
// Ошибка загрузки — игнорируем (user может быть offline)
}
}, []);
/** Отмечает одно уведомление как прочитанное. */
const markAsRead = useCallback(async (id: string): Promise<void> => {
try {
await apiFetch(`/notifications/${id}/read`, { method: 'PATCH' });
setNotifications((prev) => prev.map((n) => n.id === id ? { ...n, isRead: true } : n));
setUnreadCount((prev) => Math.max(0, prev - 1));
} catch {
// Игнорируем ошибку
}
}, []);
/** Отмечает все уведомления как прочитанные. */
const markAllAsRead = useCallback(async (): Promise<void> => {
try {
await apiFetch('/notifications/read-all', { method: 'POST' });
setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
setUnreadCount(0);
} catch {
// Игнорируем ошибку
}
}, []);
// Загружаем уведомления при монтировании (если авторизован)
useEffect(() => {
if (token !== null) {
fetchNotifications().catch(() => { /* ignore */ });
}
}, [token, fetchNotifications]);
// Подписываемся на real-time уведомления
useEffect(() => {
const onNotification = (data: NotificationItem): void => {
setNotifications((prev) => [data, ...prev]);
setUnreadCount((prev) => prev + 1);
};
if (socket !== null) {
socket.on('notification', onNotification);
return () => {
socket.off('notification', onNotification);
};
}
return undefined;
}, [socket]);
return {
notifications,
unreadCount,
fetchNotifications,
markAsRead,
markAllAsRead,
};
}
+35
View File
@@ -0,0 +1,35 @@
import { useEffect, useState } from 'react';
import { io, type Socket } from 'socket.io-client';
/**
* Подключается к Socket.IO серверу с JWT-аутентификацией.
*
* @param token — JWT токен пользователя
* @param url — URL Socket.IO сервера (по умолчанию — текущий origin)
* @returns socket или null (если не подключено)
*/
export function useSocket(token: string | null, url?: string): Socket | null {
const [socket, setSocket] = useState<Socket | null>(null);
useEffect(() => {
if (token === null || token === '') {
setSocket(null);
return undefined;
}
const socketUrl = url ?? window.location.origin;
const newSocket = io(socketUrl, {
auth: { token },
transports: ['websocket', 'polling'],
});
setSocket(newSocket);
return () => {
newSocket.disconnect();
setSocket(null);
};
}, [token, url]);
return socket;
}
+39
View File
@@ -0,0 +1,39 @@
.page {
max-width: 640px;
margin: 3rem auto;
padding: 3rem 2.5rem;
text-align: center;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
p {
margin-bottom: 1.5rem;
color: #4b5563;
}
}
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.875rem 2rem;
background: #fff;
border-bottom: 1px solid #e5e7eb;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
a {
margin-right: 1.25rem;
font-weight: 500;
}
}
.navRight {
display: flex;
align-items: center;
gap: 1rem;
button {
margin-left: 0.5rem;
}
}
+16 -10
View File
@@ -1,19 +1,23 @@
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.js'; import { useAuth } from '../auth/AuthContext.js';
import { NotificationBell } from '../components/NotificationBell.js';
import styles from './HomePage.module.scss';
/** /**
* Главная страница (защищена ProtectedRoute). * Главная страница (защищена ProtectedRoute).
* Показывает email пользователя, навигацию и кнопку logout. * Показывает email пользователя, навигацию и кнопку logout.
*/ */
export function HomePage() { export function HomePage() {
const { userEmail, logout } = useAuth(); const { userEmail, token, logout } = useAuth();
return ( return (
<div className="home-page"> <>
<nav className="top-nav"> <nav className={styles.nav}>
<span>News Editor — {userEmail}</span> <span>News Editor — {userEmail}</span>
<div> <div className={styles.navRight}>
<NotificationBell token={token} />
<Link to="/news">Мои новости</Link> <Link to="/news">Мои новости</Link>
<button type="button" onClick={logout}> <button type="button" onClick={logout}>
Выйти Выйти
@@ -21,11 +25,13 @@ export function HomePage() {
</div> </div>
</nav> </nav>
<h1>News Editor</h1> <div className={styles.page}>
<p>Добро пожаловать, {userEmail}!</p> <h1>News Editor</h1>
<Link to="/news" className="btn btn-primary"> <p>Добро пожаловать, {userEmail}!</p>
Перейти к новостям <Link to="/news" className="btn btn-primary">
</Link> Перейти к новостям
</div> </Link>
</div>
</>
); );
} }
+11 -9
View File
@@ -1,8 +1,10 @@
import { useState, type FormEvent } from 'react'; import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.js'; import { useAuth } from '../auth/AuthContext.js';
import styles from './auth.module.scss';
/** /**
* Страница логина. * Страница логина.
*/ */
@@ -29,10 +31,10 @@ export function LoginPage() {
/* eslint-enable @typescript-eslint/no-floating-promises */ /* eslint-enable @typescript-eslint/no-floating-promises */
return ( return (
<div className="auth-page"> <div className={styles.page}>
<h1>Вход</h1> <h1 className={styles.title}>Вход</h1>
<form onSubmit={handleSubmit}> <form className={styles.form} onSubmit={handleSubmit}>
<div className="form-group"> <div className={styles.group}>
<label htmlFor="email">Email</label> <label htmlFor="email">Email</label>
<input <input
id="email" id="email"
@@ -43,7 +45,7 @@ export function LoginPage() {
autoComplete="email" autoComplete="email"
/> />
</div> </div>
<div className="form-group"> <div className={styles.group}>
<label htmlFor="password">Пароль</label> <label htmlFor="password">Пароль</label>
<input <input
id="password" id="password"
@@ -55,13 +57,13 @@ export function LoginPage() {
/> />
</div> </div>
{error ? <p className="error">{error}</p> : null} {error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={loading}> <button type="submit" className={`btn btn-primary ${styles.submit}`} disabled={loading}>
{loading ? 'Вход...' : 'Войти'} {loading ? 'Вход...' : 'Войти'}
</button> </button>
</form> </form>
<p> <p className={styles.switch}>
Нет аккаунта?{' '} Нет аккаунта?{' '}
<a href="/register">Зарегистрироваться</a> <Link to="/register">Зарегистрироваться</Link>
</p> </p>
</div> </div>
); );
+114
View File
@@ -0,0 +1,114 @@
.page {
max-width: 820px;
margin: 2rem auto;
padding: 2rem 2.5rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
padding-bottom: 1.25rem;
border-bottom: 1px solid #f3f4f6;
flex-wrap: wrap;
gap: 0.75rem 1rem;
h1 {
margin-bottom: 0;
font-size: 1.4rem;
margin-right: auto;
}
}
.actions {
display: flex;
gap: 0.625rem;
flex-wrap: wrap;
}
.titleInput {
font-size: 1.3rem;
font-weight: 600;
margin-bottom: 1.5rem;
border: none;
border-bottom: 2px solid #e5e7eb;
border-radius: 0;
padding: 0.625rem 0;
&:focus {
border-bottom-color: #2563eb;
box-shadow: none;
}
}
.scheduleRow {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1.25rem;
padding: 0.75rem 1rem;
background: #fffbeb;
border: 1px solid #fde68a;
border-radius: 8px;
flex-wrap: wrap;
label {
font-size: 0.9rem;
display: flex;
align-items: center;
gap: 0.5rem;
input {
width: auto;
}
}
}
.toolbar {
display: flex;
gap: 0.25rem;
padding: 0.5rem 0.75rem;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-bottom: none;
border-radius: 6px 6px 0 0;
flex-wrap: wrap;
button {
padding: 0.4rem 0.65rem;
font-size: 0.88rem;
background: transparent;
color: #374151;
border: none;
border-radius: 4px;
cursor: pointer;
transition: background 0.1s;
&:hover {
background: #e5e7eb;
}
}
}
.textarea {
min-height: 320px;
resize: vertical;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 0.9rem;
line-height: 1.7;
border-radius: 0 0 6px 6px;
margin-bottom: 1.5rem;
}
.preview {
padding: 1.5rem 2rem;
border: 1px solid #e5e7eb;
border-radius: 8px;
background: #fafafa;
min-height: 320px;
margin-bottom: 1.5rem;
}
+45 -45
View File
@@ -1,4 +1,4 @@
import { useCallback, useRef, useState, type ChangeEvent, type RefObject } from 'react'; import { useRef, useState, type ChangeEvent, type RefObject } from 'react';
import ReactMarkdown from 'react-markdown'; import ReactMarkdown from 'react-markdown';
import { Link, useParams } from 'react-router-dom'; import { Link, useParams } from 'react-router-dom';
import rehypeSanitize from 'rehype-sanitize'; import rehypeSanitize from 'rehype-sanitize';
@@ -7,33 +7,38 @@ import remarkGfm from 'remark-gfm';
import { MarkdownToolbar } from '../components/MarkdownToolbar.js'; import { MarkdownToolbar } from '../components/MarkdownToolbar.js';
import { useNewsEditor } from '../hooks/useNewsEditor.js'; import { useNewsEditor } from '../hooks/useNewsEditor.js';
import styles from './NewsEditorPage.module.scss';
/** /**
* Панель действий редактора (кнопки). * Панель действий редактора (кнопки).
*/ */
function EditorActions({ function EditorActions({
isNew, saving, onSave, onPublish, onDelete, isNew, isPublished, saving, onSave, onPublish, onDelete,
}: { }: {
readonly isNew: boolean; readonly isNew: boolean;
readonly isPublished: boolean;
readonly saving: boolean; readonly saving: boolean;
readonly onSave: () => void; readonly onSave: () => void;
readonly onPublish: () => void; readonly onPublish: () => void;
readonly onDelete: () => void; readonly onDelete: () => void;
}) { }) {
return ( return (
<div className="editor-actions"> <div className={styles.actions}>
<button type="button" className="btn btn-primary" onClick={onSave} disabled={saving}> <button type="button" className="btn btn-primary" onClick={onSave} disabled={saving}>
Сохранить Сохранить
</button> </button>
{!isNew && !isPublished
? (
<button type="button" className="btn btn-publish" onClick={onPublish} disabled={saving}>
Опубликовать
</button>
)
: null}
{!isNew {!isNew
? ( ? (
<> <button type="button" className="btn btn-delete" onClick={onDelete} disabled={saving}>
<button type="button" className="btn btn-publish" onClick={onPublish} disabled={saving}> Удалить
Опубликовать </button>
</button>
<button type="button" className="btn btn-delete" onClick={onDelete} disabled={saving}>
Удалить
</button>
</>
) )
: null} : null}
</div> </div>
@@ -52,7 +57,7 @@ function ScheduleRow({
readonly onSchedule: () => void; readonly onSchedule: () => void;
}) { }) {
return ( return (
<div className="schedule-row"> <div className={styles.scheduleRow}>
<label> <label>
Отложенная публикация:{' '} Отложенная публикация:{' '}
<input <input
@@ -93,11 +98,13 @@ function EditorForm({
}) { }) {
return ( return (
<> <>
<MarkdownToolbar onAction={onAction} onImageUpload={onImageUpload} onFileUpload={onFileUpload} /> <div className={styles.toolbar}>
<MarkdownToolbar onAction={onAction} onImageUpload={onImageUpload} onFileUpload={onFileUpload} />
</div>
<textarea <textarea
ref={textareaRef} ref={textareaRef}
className="editor-textarea" className={styles.textarea}
value={content} value={content}
onChange={(e) => { setContent(e.target.value); }} onChange={(e) => { setContent(e.target.value); }}
placeholder="Напишите текст в Markdown..." placeholder="Напишите текст в Markdown..."
@@ -127,10 +134,10 @@ function EditorForm({
*/ */
function EditorPreview({ content }: { readonly content: string }) { function EditorPreview({ content }: { readonly content: string }) {
if (content === '') { if (content === '') {
return <div className="editor-preview markdown-body"><p className="empty">Нет контента для предпросмотра</p></div>; return <div className={styles.preview}><p className="empty">Нет контента для предпросмотра</p></div>;
} }
return ( return (
<div className="editor-preview markdown-body"> <div className={`${styles.preview} markdown-body`}>
<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeSanitize]}> <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeSanitize]}>
{content} {content}
</ReactMarkdown> </ReactMarkdown>
@@ -143,64 +150,57 @@ function EditorPreview({ content }: { readonly content: string }) {
*/ */
export function NewsEditorPage() { export function NewsEditorPage() {
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const [showPreview, setShowPreview] = useState(false); const [showPreview, setShowPreview] = useState(id !== undefined);
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const imageInputRef = useRef<HTMLInputElement>(null); const imageInputRef = useRef<HTMLInputElement>(null);
const editor = useNewsEditor(id); const editor = useNewsEditor(id);
const { const {
isNew, title, setTitle, content, setContent, isNew, title, setTitle, content, setContent, newsStatus,
loading, saving, error, loading, saving, error,
scheduleDate, setScheduleDate, textareaRef, scheduleDate, setScheduleDate, textareaRef,
handleToolbarAction, handleFileUpload, handleToolbarAction, onImageChange, onFileChange,
onSave, onPublish, onDelete, onSchedule, onSave, onPublish, onDelete, onSchedule,
} = editor; } = editor;
const onImageChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, true).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input для повторной загрузки
e.target.value = '';
}, [handleFileUpload]);
const onFileChange = useCallback((e: ChangeEvent<HTMLInputElement>): void => {
const file = e.target.files?.[0];
if (file !== undefined) {
handleFileUpload(file, false).catch((err: unknown) => { console.error(err); });
}
// eslint-disable-next-line no-param-reassign -- сброс file input для повторной загрузки
e.target.value = '';
}, [handleFileUpload]);
if (loading) { if (loading) {
return <p className="loading">Загрузка...</p>; return <p className="loading">Загрузка...</p>;
} }
return ( return (
<div className="news-editor"> <div className={styles.page}>
<div className="editor-header"> <div className={styles.header}>
<Link to="/news" className="btn btn-back">← Назад</Link> <Link to="/news" className="btn btn-back">← Назад</Link>
<h1>{isNew ? 'Новая новость' : 'Редактирование'}</h1> <h1>{isNew ? 'Новая новость' : 'Редактирование'}</h1>
<EditorActions isNew={isNew} saving={saving} onSave={onSave} onPublish={onPublish} onDelete={onDelete} /> <EditorActions
<button type="button" className="btn" onClick={() => { setShowPreview((v) => !v); }}> isNew={isNew}
{showPreview ? 'Редактор' : 'Предпросмотр'} isPublished={newsStatus === 'published'}
</button> saving={saving}
onSave={onSave}
onPublish={onPublish}
onDelete={onDelete}
/>
{newsStatus !== 'published'
? (
<button type="button" className="btn" onClick={() => { setShowPreview((v) => !v); }}>
{showPreview ? 'Редактор' : 'Предпросмотр'}
</button>
)
: null}
</div> </div>
{error !== '' && <p className="error">{error}</p>} {error !== '' && <p className="error">{error}</p>}
<input <input
type="text" type="text"
className="title-input" className={styles.titleInput}
placeholder="Заголовок..." placeholder="Заголовок..."
value={title} value={title}
onChange={(e) => { setTitle(e.target.value); }} onChange={(e) => { setTitle(e.target.value); }}
/> />
{!isNew {!isNew && newsStatus !== 'published'
? ( ? (
<ScheduleRow <ScheduleRow
scheduleDate={scheduleDate} scheduleDate={scheduleDate}
+104
View File
@@ -0,0 +1,104 @@
.page {
max-width: 720px;
margin: 2rem auto;
padding: 2rem 2.5rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
padding-bottom: 1rem;
border-bottom: 1px solid #f3f4f6;
h1 {
font-size: 1.4rem;
margin-bottom: 0;
}
}
.list {
list-style: none;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.card {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 1rem;
padding: 1rem 1.25rem;
background: #fafbfc;
border: 1px solid #f3f4f6;
border-radius: 8px;
transition: box-shadow 0.15s, border-color 0.15s;
&:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
border-color: #e5e7eb;
}
}
.cardBody {
flex: 1;
min-width: 0;
}
.cardTitle {
font-weight: 600;
display: block;
margin-bottom: 0.25rem;
}
.cardPreview {
font-size: 0.85rem;
color: #6b7280;
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.cardMeta {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 0.35rem;
flex-shrink: 0;
}
.cardDate {
font-size: 0.78rem;
color: #9ca3af;
}
.badge {
font-size: 0.72rem;
padding: 0.2rem 0.55rem;
border-radius: 4px;
font-weight: 600;
white-space: nowrap;
&.draft {
background: #f3f4f6;
color: #6b7280;
}
&.scheduled {
background: #fef3c7;
color: #92400e;
}
&.published {
background: #d1fae5;
color: #065f46;
}
}
+23 -11
View File
@@ -3,8 +3,11 @@ import { Link } from 'react-router-dom';
import { apiFetch } from '../api/client.js'; import { apiFetch } from '../api/client.js';
import styles from './NewsListPage.module.scss';
import type { NewsItem } from '../api/types.js'; import type { NewsItem } from '../api/types.js';
/** /**
* Страница со списком новостей текущего пользователя. * Страница со списком новостей текущего пользователя.
*/ */
@@ -32,8 +35,8 @@ export function NewsListPage() {
} }
return ( return (
<div className="news-list"> <div className={styles.page}>
<div className="news-list-header"> <div className={styles.header}>
<h1>Мои новости</h1> <h1>Мои новости</h1>
<Link to="/news/new" className="btn btn-primary"> <Link to="/news/new" className="btn btn-primary">
+ Создать + Создать
@@ -45,16 +48,25 @@ export function NewsListPage() {
{news.length === 0 {news.length === 0
? <p className="empty">Нет новостей. Создайте первую!</p> ? <p className="empty">Нет новостей. Создайте первую!</p>
: ( : (
<ul className="news-cards"> <ul className={styles.list}>
{news.map((item) => ( {news.map((item) => (
<li key={item.id} className="news-card"> <li key={item.id} className={styles.card}>
<Link to={`/news/${item.id}`} className="news-card-title"> <div className={styles.cardBody}>
{item.title !== '' ? item.title : '(без названия)'} <Link to={`/news/${item.id}`} className={styles.cardTitle}>
</Link> {item.title !== '' ? item.title : '(без названия)'}
<span className={`badge badge-${item.status}`}>{item.status}</span> </Link>
<span className="news-card-date"> {item.content !== '' && (
{new Date(item.updatedAt).toLocaleString('ru-RU')} <p className={styles.cardPreview}>
</span> {item.content.replace(/[#*`[\]!\n]/g, '').slice(0, 120)}
</p>
)}
</div>
<div className={styles.cardMeta}>
<span className={`${styles.badge} ${styles[item.status]}`}>{item.status}</span>
<span className={styles.cardDate}>
{new Date(item.updatedAt).toLocaleString('ru-RU')}
</span>
</div>
</li> </li>
))} ))}
</ul> </ul>
+12 -10
View File
@@ -1,8 +1,10 @@
import { useState, type FormEvent } from 'react'; import { useState, type FormEvent } from 'react';
import { useNavigate } from 'react-router-dom'; import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../auth/AuthContext.js'; import { useAuth } from '../auth/AuthContext.js';
import styles from './auth.module.scss';
/** /**
* Страница регистрации. * Страница регистрации.
*/ */
@@ -34,10 +36,10 @@ export function RegisterPage() {
/* eslint-enable @typescript-eslint/no-floating-promises */ /* eslint-enable @typescript-eslint/no-floating-promises */
return ( return (
<div className="auth-page"> <div className={styles.page}>
<h1>Регистрация</h1> <h1 className={styles.title}>Регистрация</h1>
<form onSubmit={handleSubmit}> <form className={styles.form} onSubmit={handleSubmit}>
<div className="form-group"> <div className={styles.group}>
<label htmlFor="email">Email</label> <label htmlFor="email">Email</label>
<input <input
id="email" id="email"
@@ -48,7 +50,7 @@ export function RegisterPage() {
autoComplete="email" autoComplete="email"
/> />
</div> </div>
<div className="form-group"> <div className={styles.group}>
<label htmlFor="password">Пароль</label> <label htmlFor="password">Пароль</label>
<input <input
id="password" id="password"
@@ -60,7 +62,7 @@ export function RegisterPage() {
autoComplete="new-password" autoComplete="new-password"
/> />
</div> </div>
<div className="form-group"> <div className={styles.group}>
<label htmlFor="confirmPassword">Повторите пароль</label> <label htmlFor="confirmPassword">Повторите пароль</label>
<input <input
id="confirmPassword" id="confirmPassword"
@@ -72,13 +74,13 @@ export function RegisterPage() {
/> />
</div> </div>
{error ? <p className="error">{error}</p> : null} {error ? <p className="error">{error}</p> : null}
<button type="submit" disabled={loading}> <button type="submit" className={`btn btn-primary ${styles.submit}`} disabled={loading}>
{loading ? 'Регистрация...' : 'Зарегистрироваться'} {loading ? 'Регистрация...' : 'Зарегистрироваться'}
</button> </button>
</form> </form>
<p> <p className={styles.switch}>
Уже есть аккаунт?{' '} Уже есть аккаунт?{' '}
<a href="/login">Войти</a> <Link to="/login">Войти</Link>
</p> </p>
</div> </div>
); );
+46
View File
@@ -0,0 +1,46 @@
.page {
max-width: 400px;
margin: 3rem auto;
padding: 2rem 2.5rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}
.title {
font-size: 1.4rem;
margin-bottom: 1.5rem;
text-align: center;
}
.form {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.group {
display: flex;
flex-direction: column;
gap: 0.35rem;
label {
font-weight: 500;
font-size: 0.9rem;
}
}
.submit {
margin-top: 0.5rem;
}
.switch {
margin-top: 1.5rem;
text-align: center;
font-size: 0.9rem;
color: #6b7280;
a {
margin-left: 0.25rem;
}
}
+34 -249
View File
@@ -1,4 +1,4 @@
// Глобальные стили News Editor // Глобальные стили News Editor (base + shared utilities)
* { * {
box-sizing: border-box; box-sizing: border-box;
@@ -10,7 +10,7 @@ body {
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
line-height: 1.6; line-height: 1.6;
color: #1a1a2e; color: #1a1a2e;
background: #f5f5f5; background: #f0f2f5;
} }
a { a {
@@ -27,25 +27,6 @@ h1 {
font-size: 1.8rem; font-size: 1.8rem;
} }
button {
padding: 0.5rem 1.2rem;
border: none;
border-radius: 6px;
background: #2563eb;
color: #fff;
font-size: 0.95rem;
cursor: pointer;
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
&:hover:not(:disabled) {
background: #1d4ed8;
}
}
input, input,
textarea { textarea {
width: 100%; width: 100%;
@@ -62,7 +43,7 @@ textarea {
} }
} }
// Кнопки // === Shared: Кнопки ===
.btn { .btn {
display: inline-block; display: inline-block;
padding: 0.5rem 1.2rem; padding: 0.5rem 1.2rem;
@@ -73,17 +54,23 @@ textarea {
text-decoration: none; text-decoration: none;
background: #e5e7eb; background: #e5e7eb;
color: #1a1a2e; color: #1a1a2e;
transition: background 0.15s;
&:hover { &:hover {
background: #d1d5db; background: #d1d5db;
text-decoration: none; text-decoration: none;
} }
&:disabled {
opacity: 0.6;
cursor: not-allowed;
}
&-primary { &-primary {
background: #2563eb; background: #2563eb;
color: #fff; color: #fff;
&:hover { &:hover:not(:disabled) {
background: #1d4ed8; background: #1d4ed8;
} }
} }
@@ -92,7 +79,7 @@ textarea {
background: #16a34a; background: #16a34a;
color: #fff; color: #fff;
&:hover { &:hover:not(:disabled) {
background: #15803d; background: #15803d;
} }
} }
@@ -101,7 +88,7 @@ textarea {
background: #f59e0b; background: #f59e0b;
color: #fff; color: #fff;
&:hover { &:hover:not(:disabled) {
background: #d97706; background: #d97706;
} }
} }
@@ -110,7 +97,7 @@ textarea {
background: #dc2626; background: #dc2626;
color: #fff; color: #fff;
&:hover { &:hover:not(:disabled) {
background: #b91c1c; background: #b91c1c;
} }
} }
@@ -119,37 +106,21 @@ textarea {
background: transparent; background: transparent;
color: #2563eb; color: #2563eb;
&:hover { &:hover:not(:disabled) {
background: #eff6ff; background: #eff6ff;
} }
} }
} }
// Страница авторизации // === Shared: Error / Loading / Empty ===
.auth-page {
max-width: 400px;
margin: 4rem auto;
padding: 2rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.form-group {
margin-bottom: 1rem;
label {
display: block;
margin-bottom: 0.25rem;
font-weight: 500;
font-size: 0.9rem;
}
}
.error { .error {
color: #dc2626; color: #dc2626;
font-size: 0.9rem; font-size: 0.9rem;
margin-bottom: 0.75rem; margin-bottom: 1rem;
padding: 0.5rem 0.75rem;
background: #fef2f2;
border-radius: 6px;
border: 1px solid #fecaca;
} }
.loading, .loading,
@@ -158,219 +129,32 @@ textarea {
font-style: italic; font-style: italic;
} }
// Навигация // === Markdown body (используется в preview) ===
.top-nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem 1.5rem;
background: #fff;
border-bottom: 1px solid #e5e7eb;
a {
margin-right: 1rem;
}
button {
margin-left: 0.5rem;
}
}
// Главная страница
.home-page {
max-width: 600px;
margin: 2rem auto;
padding: 2rem;
text-align: center;
p {
margin-bottom: 1.5rem;
}
}
// Список новостей
.news-list {
max-width: 700px;
margin: 2rem auto;
padding: 1.5rem;
&-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
}
}
.news-cards {
list-style: none;
.news-card {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 1rem;
background: #fff;
border-radius: 8px;
margin-bottom: 0.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
&-title {
flex: 1;
font-weight: 600;
}
&-date {
font-size: 0.8rem;
color: #6b7280;
}
}
}
.badge {
font-size: 0.75rem;
padding: 0.15rem 0.5rem;
border-radius: 4px;
font-weight: 500;
&-draft {
background: #f3f4f6;
color: #6b7280;
}
&-scheduled {
background: #fef3c7;
color: #92400e;
}
&-published {
background: #d1fae5;
color: #065f46;
}
}
// Редактор
.news-editor {
max-width: 800px;
margin: 1.5rem auto;
padding: 1.5rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
&-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
flex-wrap: wrap;
gap: 0.5rem;
h1 {
margin-bottom: 0;
font-size: 1.4rem;
}
}
&-actions {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
}
.title-input {
font-size: 1.3rem;
font-weight: 600;
margin-bottom: 1rem;
border: none;
border-bottom: 2px solid #e5e7eb;
border-radius: 0;
padding: 0.5rem 0;
&:focus {
border-bottom-color: #2563eb;
box-shadow: none;
}
}
.schedule-row {
display: flex;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
flex-wrap: wrap;
label {
font-size: 0.9rem;
display: flex;
align-items: center;
gap: 0.5rem;
input {
width: auto;
}
}
}
// Markdown toolbar
.markdown-toolbar {
display: flex;
gap: 0.25rem;
padding: 0.5rem;
background: #f9fafb;
border: 1px solid #e5e7eb;
border-bottom: none;
border-radius: 6px 6px 0 0;
button {
padding: 0.35rem 0.6rem;
font-size: 0.9rem;
background: transparent;
color: #374151;
border-radius: 4px;
&:hover {
background: #e5e7eb;
}
}
}
.editor-textarea {
min-height: 300px;
resize: vertical;
font-family: 'JetBrains Mono', 'Fira Code', monospace;
font-size: 0.9rem;
border-radius: 0 0 6px 6px;
margin-bottom: 1rem;
}
// Markdown preview
.markdown-body { .markdown-body {
padding: 1.5rem;
border: 1px solid #e5e7eb;
border-radius: 6px;
background: #fafafa;
min-height: 300px;
h1, h2, h3 { h1, h2, h3 {
margin: 1rem 0 0.5rem; margin: 1.25rem 0 0.5rem;
&:first-child {
margin-top: 0;
}
} }
p { p {
margin-bottom: 0.75rem; margin-bottom: 0.875rem;
} }
blockquote { blockquote {
border-left: 4px solid #2563eb; border-left: 4px solid #2563eb;
padding-left: 1rem; padding: 0.5rem 1rem;
margin: 1rem 0; margin: 1rem 0;
color: #4b5563; color: #4b5563;
background: #f8faff;
border-radius: 0 4px 4px 0;
} }
code { code {
background: #f3f4f6; background: #f3f4f6;
padding: 0.15rem 0.35rem; padding: 0.15rem 0.4rem;
border-radius: 3px; border-radius: 3px;
font-size: 0.85em; font-size: 0.85em;
} }
@@ -378,7 +162,7 @@ textarea {
pre { pre {
background: #1f2937; background: #1f2937;
color: #e5e7eb; color: #e5e7eb;
padding: 1rem; padding: 1.25rem 1.5rem;
border-radius: 6px; border-radius: 6px;
overflow-x: auto; overflow-x: auto;
margin: 1rem 0; margin: 1rem 0;
@@ -402,12 +186,13 @@ textarea {
th, td { th, td {
border: 1px solid #e5e7eb; border: 1px solid #e5e7eb;
padding: 0.5rem; padding: 0.6rem 0.75rem;
text-align: left; text-align: left;
} }
th { th {
background: #f9fafb; background: #f9fafb;
font-weight: 600;
} }
} }
} }
+27 -10
View File
@@ -7,27 +7,43 @@ import { errorHandler } from './middleware/error.middleware.js';
import { notFoundHandler } from './middleware/notFound.middleware.js'; import { notFoundHandler } from './middleware/notFound.middleware.js';
import authRouter from './routes/auth.routes.js'; import authRouter from './routes/auth.routes.js';
import healthRouter from './routes/health.routes.js'; import healthRouter from './routes/health.routes.js';
import newsRouter from './routes/news.routes.js'; import { createNewsRouter } from './routes/news.routes.js';
import notificationRouter from './routes/notification.routes.js';
import uploadRouter from './routes/upload.routes.js'; import uploadRouter from './routes/upload.routes.js';
import type { Server as SocketIOServer } from 'socket.io';
/**
* Параметры для создания приложения.
*/
interface CreateAppOptions {
/** Экземпляр Socket.IO server (передаётся в news routes для emit). */
readonly io?: SocketIOServer;
/** Дополнительные middleware (тесты). */
readonly extraMiddleware?: express.RequestHandler;
}
/** /**
* Создаёт и настраивает Express-приложение. * Создаёт и настраивает Express-приложение.
* *
* Функция (а не готовый экземпляр) позволяет тестам создавать * @param options — параметры (io, extraMiddleware)
* независимые приложения без побочных эффектов.
*
* @param extraMiddleware — дополнительные middleware, подключаемые
* после роутеров и до терминальных обработчиков (используется в тестах
* для проверки error middleware на контролируемых путях)
* @returns настроенное Express-приложение * @returns настроенное Express-приложение
*/ */
export function createApp(extraMiddleware?: express.RequestHandler): express.Express { export function createApp(options?: CreateAppOptions): express.Express {
const app = express(); const app = express();
const { io, extraMiddleware } = options ?? {};
// /socket.io — Socket.IO (engine.io) обрабатывает на уровне HTTP server.
// Express НЕ отвечает на эти запросы (не вызывает res.send/next).
// Socket.IO handler (второй listener) получает те же req/res и отвечает.
app.use('/socket.io', () => {
// Intentionally empty — не отвечаем, Socket.IO обработает
});
// Security headers // Security headers
app.use(helmet()); app.use(helmet());
// CORS — whitelist из CLIENT_ORIGIN (поддерживается несколько через запятую) // CORS — whitelist из CLIENT_ORIGIN
app.use(cors({ origin: env.clientOrigins })); app.use(cors({ origin: env.clientOrigins }));
// Парсинг тела запроса // Парсинг тела запроса
@@ -41,7 +57,8 @@ export function createApp(extraMiddleware?: express.RequestHandler): express.Exp
// API-маршруты // API-маршруты
app.use('/api', healthRouter); app.use('/api', healthRouter);
app.use('/api/auth', authRouter); app.use('/api/auth', authRouter);
app.use('/api/news', newsRouter); app.use('/api/news', createNewsRouter(io));
app.use('/api/notifications', notificationRouter);
app.use('/api/uploads', uploadRouter); app.use('/api/uploads', uploadRouter);
// Дополнительные middleware (тестовые маршруты, заглушки) // Дополнительные middleware (тестовые маршруты, заглушки)
@@ -25,6 +25,11 @@ function errorMessageOf(err: unknown): string {
*/ */
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- сигнатура Express требует 4 аргумента // eslint-disable-next-line @typescript-eslint/no-unused-vars -- сигнатура Express требует 4 аргумента
export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => { export const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {
// Если ответ уже отправлен (Socket.IO) — не дублируем
if (res.headersSent) {
return;
}
// Ожидаемая ошибка — возвращаем её статус и код // Ожидаемая ошибка — возвращаем её статус и код
if (err instanceof ApiError) { if (err instanceof ApiError) {
res.status(err.status).json({ error: { code: err.code, message: err.message } }); res.status(err.status).json({ error: { code: err.code, message: err.message } });
+5 -1
View File
@@ -8,6 +8,10 @@ import type { NextFunction, Request, Response } from 'express';
* Вызывается после всех маршрутизаторов и передаёт ошибку 404 * Вызывается после всех маршрутизаторов и передаёт ошибку 404
* в централизованный error middleware. * в централизованный error middleware.
*/ */
export function notFoundHandler(req: Request, _res: Response, next: NextFunction): void { export function notFoundHandler(req: Request, res: Response, next: NextFunction): void {
// Если ответ уже отправлен (Socket.IO) — не дублируем
if (res.headersSent) {
return;
}
next(new ApiError(404, 'NOT_FOUND', `Маршрут не найден: ${req.method} ${req.originalUrl}`)); next(new ApiError(404, 'NOT_FOUND', `Маршрут не найден: ${req.method} ${req.originalUrl}`));
} }
+72
View File
@@ -0,0 +1,72 @@
import { Schema, model, type HydratedDocument, type Types } from 'mongoose';
/** Тип уведомления о действиях с новостью. */
export type NotificationType = 'news.created' | 'news.updated' | 'news.deleted' | 'news.scheduled' | 'news.published';
export interface INotification {
/** Получатель уведомления. */
user: Types.ObjectId;
/** Кто совершил действие (может совпадать с user). */
actor: Types.ObjectId | null;
/** Тип события. */
type: NotificationType;
/** Ссылка на новость (если применимо). */
news: Types.ObjectId | null;
/** Заголовок уведомления. */
title: string;
/** Тело сообщения. */
message: string;
/** Прочитано ли. */
isRead: boolean;
createdAt: Date;
}
export type NotificationDocument = HydratedDocument<INotification>;
const notificationSchema = new Schema<INotification>(
{
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: [true, 'Получатель уведомления обязателен'],
},
actor: {
type: Schema.Types.ObjectId,
ref: 'User',
default: null,
},
type: {
type: String,
enum: ['news.created', 'news.updated', 'news.deleted', 'news.scheduled', 'news.published'],
required: [true, 'Тип уведомления обязателен'],
},
news: {
type: Schema.Types.ObjectId,
ref: 'News',
default: null,
},
title: {
type: String,
required: [true, 'Заголовок уведомления обязателен'],
trim: true,
},
message: {
type: String,
default: '',
},
isRead: {
type: Boolean,
default: false,
},
},
{
timestamps: { createdAt: true, updatedAt: false },
},
);
// Индекс для быстрого поиска непрочитанных
notificationSchema.index({ user: 1, isRead: 1, createdAt: -1 });
const Notification = model<INotification>('Notification', notificationSchema);
export default Notification;
+59 -120
View File
@@ -2,25 +2,16 @@ import { Router, type Request, type Response } from 'express';
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js'; import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
import News from '../models/news.model.js'; import News from '../models/news.model.js';
import { createNotification } from '../services/notification.service.js';
import { ApiError } from '../utils/ApiError.js'; import { ApiError } from '../utils/ApiError.js';
import { asyncHandler } from '../utils/asyncHandler.js'; import { asyncHandler } from '../utils/asyncHandler.js';
const newsRouter = Router(); import type { Server as SocketIOServer } from 'socket.io';
// Сообщение об авторизации
const AUTH_MSG = 'Требуется авторизация'; const AUTH_MSG = 'Требуется авторизация';
// Сообщение о не найденной новости
const NOT_FOUND_MSG = 'Новость не найдена'; const NOT_FOUND_MSG = 'Новость не найдена';
// Все маршруты требуют авторизацию /** Возвращает id авторизованного пользователя. */
newsRouter.use(requireAuth);
/**
* Возвращает id авторизованного пользователя или бросает 401.
*
* @param req — запрос Express
* @returns id пользователя (string)
*/
function getUserId(req: Request): string { function getUserId(req: Request): string {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
const authedReq = req as AuthenticatedRequest; const authedReq = req as AuthenticatedRequest;
@@ -30,25 +21,14 @@ function getUserId(req: Request): string {
return authedReq.user.id; return authedReq.user.id;
} }
/** /** Безопасно извлекает поле из req.body. */
* Безопасно извлекает поле из req.body (any → unknown).
*
* @param req — запрос Express
* @param key — имя поля
* @returns значение поля (unknown)
*/
function bodyField(req: Request, key: string): unknown { function bodyField(req: Request, key: string): unknown {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- req.body из express // eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-unsafe-type-assertion -- req.body из express typed as any
const raw = (req.body ?? {}) as Record<string, unknown>; const raw = (req.body ?? {}) as Record<string, unknown>;
return raw[key]; return raw[key];
} }
/** /** Форматирует документ новости для JSON. */
* Форматирует Mongoose-документ новости для JSON-ответа.
*
* @param n — документ Mongoose
* @returns объект с публичными полями
*/
function serializeNews(n: InstanceType<typeof News>) { function serializeNews(n: InstanceType<typeof News>) {
return { return {
id: n._id, id: n._id,
@@ -63,89 +43,58 @@ function serializeNews(n: InstanceType<typeof News>) {
} }
/** /**
* GET /api/news * Создаёт news router с привязкой к Socket.IO серверу.
* Список новостей пользователя (все статусы).
* *
* @returns 200 { news: [...] } * @param io — Socket.IO server для отправки real-time событий
* @returns настроенный Router
*/ */
newsRouter.get( /* eslint-disable max-lines-per-function -- factory-функция с 6 inline handlers (стандартный Express-паттерн) */
'/', export function createNewsRouter(io?: SocketIOServer): Router {
asyncHandler(async (req: Request, res: Response) => { const router = Router();
router.use(requireAuth);
router.get('/', asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req); const userId = getUserId(req);
const items = await News.find({ author: userId }).sort({ createdAt: -1 }); const items = await News.find({ author: userId }).sort({ createdAt: -1 });
res.json({ news: items.map(serializeNews) }); res.json({ news: items.map(serializeNews) });
}), }));
);
/** router.get('/:id', asyncHandler(async (req: Request, res: Response) => {
* GET /api/news/:id
* Одна новость. Ownership: только свои статьи.
*
* @returns 200 { news: { id, title, content, status, ... } }
*/
newsRouter.get(
'/:id',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req); const userId = getUserId(req);
const news = await News.findOne({ _id: req.params.id, author: userId }); const news = await News.findOne({ _id: req.params.id, author: userId });
if (!news) { if (!news) {
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG); throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
} }
res.json({ news: serializeNews(news) }); res.json({ news: serializeNews(news) });
}), }));
);
/** router.post('/', asyncHandler(async (req: Request, res: Response) => {
* POST /api/news
* Создаёт новость (draft).
*
* @returns 201 { news: { id, title, content, status, ... } }
*/
newsRouter.post(
'/',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req); const userId = getUserId(req);
const title = bodyField(req, 'title'); const title = bodyField(req, 'title');
const content = bodyField(req, 'content'); const content = bodyField(req, 'content');
if (typeof title !== 'string' || title.trim().length === 0) { if (typeof title !== 'string' || title.trim().length === 0) {
throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно'); throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно');
} }
if (title.trim().length > 200) { if (title.trim().length > 200) {
throw new ApiError(400, 'VALIDATION_ERROR', 'Название не должно превышать 200 символов'); throw new ApiError(400, 'VALIDATION_ERROR', 'Название не должно превышать 200 символов');
} }
const news = await News.create({ const news = await News.create({
title: title.trim(), title: title.trim(),
content: typeof content === 'string' ? content : '', content: typeof content === 'string' ? content : '',
status: 'draft', status: 'draft',
author: userId, author: userId,
}); });
res.status(201).json({ news: serializeNews(news) }); res.status(201).json({ news: serializeNews(news) });
}), }));
);
/** router.patch('/:id', asyncHandler(async (req: Request, res: Response) => {
* PATCH /api/news/:id
* Обновляет title и/или content. Ownership: только свои статьи.
*
* @returns 200 { news: { id, title, content, status, ... } }
*/
newsRouter.patch(
'/:id',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req); const userId = getUserId(req);
const news = await News.findOne({ _id: req.params.id, author: userId }); const news = await News.findOne({ _id: req.params.id, author: userId });
if (!news) { if (!news) {
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG); throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
} }
const title = bodyField(req, 'title'); const title = bodyField(req, 'title');
const content = bodyField(req, 'content'); const content = bodyField(req, 'content');
if (title !== undefined) { if (title !== undefined) {
if (typeof title !== 'string' || title.trim().length === 0) { if (typeof title !== 'string' || title.trim().length === 0) {
throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно'); throw new ApiError(400, 'VALIDATION_ERROR', 'Название обязательно');
@@ -155,93 +104,72 @@ newsRouter.patch(
} }
news.title = title.trim(); news.title = title.trim();
} }
if (content !== undefined) { if (content !== undefined) {
if (typeof content !== 'string') { if (typeof content !== 'string') {
throw new ApiError(400, 'VALIDATION_ERROR', 'Контент должен быть строкой'); throw new ApiError(400, 'VALIDATION_ERROR', 'Контент должен быть строкой');
} }
news.content = content; news.content = content;
} }
await news.save(); await news.save();
res.json({ news: serializeNews(news) }); res.json({ news: serializeNews(news) });
}), }));
);
/** router.delete('/:id', asyncHandler(async (req: Request, res: Response) => {
* DELETE /api/news/:id
* Удаляет новость. Ownership: только свои статьи.
*
* @returns 204
*/
newsRouter.delete(
'/:id',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req); const userId = getUserId(req);
const news = await News.findOne({ _id: req.params.id, author: userId }); const news = await News.findOne({ _id: req.params.id, author: userId });
if (!news) { if (!news) {
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG); throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
} }
const title = news.title;
await news.deleteOne(); await news.deleteOne();
if (io) {
await createNotification(io, {
user: userId, actor: userId, type: 'news.deleted',
newsId: String(req.params.id),
title: 'Новость удалена',
message: `«${title}» была удалена`,
});
}
res.status(204).send(); res.status(204).send();
}), }));
);
/** router.post('/:id/publish', asyncHandler(async (req: Request, res: Response) => {
* POST /api/news/:id/publish
* Немедленная публикация новости.
*
* @returns 200 { news: { id, title, content, status: 'published', ... } }
*/
newsRouter.post(
'/:id/publish',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req); const userId = getUserId(req);
const news = await News.findOne({ _id: req.params.id, author: userId }); const news = await News.findOne({ _id: req.params.id, author: userId });
if (!news) { if (!news) {
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG); throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
} }
if (news.status === 'published') { if (news.status === 'published') {
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована'); throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
} }
news.status = 'published'; news.status = 'published';
news.publishedAt = new Date(); news.publishedAt = new Date();
news.scheduledAt = null; news.scheduledAt = null;
await news.save(); await news.save();
if (io) {
await createNotification(io, {
user: userId, actor: userId, type: 'news.published',
newsId: String(news._id),
title: 'Новость опубликована',
message: `«${news.title}» была опубликована`,
});
}
res.json({ news: serializeNews(news) }); res.json({ news: serializeNews(news) });
}), }));
);
/** router.post('/:id/schedule', asyncHandler(async (req: Request, res: Response) => {
* POST /api/news/:id/schedule
* Отложенная публикация: устанавливает scheduledAt.
*
* @param req.body.scheduledAt — ISO-дата будущего времени
* @returns 200 { news: { id, ..., status: 'scheduled', scheduledAt } }
*/
newsRouter.post(
'/:id/schedule',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req); const userId = getUserId(req);
const news = await News.findOne({ _id: req.params.id, author: userId }); const news = await News.findOne({ _id: req.params.id, author: userId });
if (!news) { if (!news) {
throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG); throw new ApiError(404, 'NEWS_NOT_FOUND', NOT_FOUND_MSG);
} }
if (news.status === 'published') { if (news.status === 'published') {
throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована'); throw new ApiError(400, 'ALREADY_PUBLISHED', 'Новость уже опубликована');
} }
const scheduledAtRaw = bodyField(req, 'scheduledAt'); const scheduledAtRaw = bodyField(req, 'scheduledAt');
if (typeof scheduledAtRaw !== 'string') { if (typeof scheduledAtRaw !== 'string') {
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть строкой (ISO-дата)'); throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть строкой (ISO-дата)');
} }
const scheduledAt = new Date(scheduledAtRaw); const scheduledAt = new Date(scheduledAtRaw);
if (Number.isNaN(scheduledAt.getTime())) { if (Number.isNaN(scheduledAt.getTime())) {
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt не является валидной датой'); throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt не является валидной датой');
@@ -249,14 +177,25 @@ newsRouter.post(
if (scheduledAt.getTime() <= Date.now()) { if (scheduledAt.getTime() <= Date.now()) {
throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть в будущем'); throw new ApiError(400, 'VALIDATION_ERROR', 'scheduledAt должен быть в будущем');
} }
news.status = 'scheduled'; news.status = 'scheduled';
news.scheduledAt = scheduledAt; news.scheduledAt = scheduledAt;
news.publishedAt = null; news.publishedAt = null;
await news.save(); await news.save();
if (io) {
await createNotification(io, {
user: userId, actor: userId, type: 'news.scheduled',
newsId: String(news._id),
title: 'Публикация запланирована',
message: `«${news.title}» запланирована на ${scheduledAt.toISOString()}`,
});
}
res.json({ news: serializeNews(news) }); res.json({ news: serializeNews(news) });
}), }));
);
return router;
}
/* eslint-enable max-lines-per-function */
/** Дефолтный экспорт (без Socket.IO). */
const newsRouter = createNewsRouter();
export default newsRouter; export default newsRouter;
+122
View File
@@ -0,0 +1,122 @@
import { Router, type Request, type Response } from 'express';
import { requireAuth, type AuthenticatedRequest } from '../middleware/auth.middleware.js';
import Notification from '../models/notification.model.js';
import { ApiError } from '../utils/ApiError.js';
import { asyncHandler } from '../utils/asyncHandler.js';
const notificationRouter = Router();
// Все маршруты требуют авторизацию
notificationRouter.use(requireAuth);
/**
* Извлекает id пользователя из авторизованного запроса.
*
* @param req — запрос Express
* @returns id пользователя
*/
function getUserId(req: Request): string {
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- req расширен middleware
const authedReq = req as AuthenticatedRequest;
if (!authedReq.user) {
throw new ApiError(401, 'UNAUTHORIZED', 'Требуется авторизация');
}
return authedReq.user.id;
}
/**
* Форматирует документ уведомления для JSON.
*
* @param n — документ Mongoose
* @returns объект с публичными полями
*/
function serializeNotification(n: InstanceType<typeof Notification>) {
return {
id: n._id,
actor: n.actor,
type: n.type,
news: n.news,
title: n.title,
message: n.message,
isRead: n.isRead,
createdAt: n.createdAt,
};
}
/**
* GET /api/notifications
* Список уведомлений текущего пользователя (последние 50).
*
* @returns 200 { notifications: [...] }
*/
notificationRouter.get(
'/',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req);
const items = await Notification.find({ user: userId })
.sort({ createdAt: -1 })
.limit(50);
res.json({ notifications: items.map(serializeNotification) });
}),
);
/**
* GET /api/notifications/unread-count
* Количество непрочитанных уведомлений.
*
* @returns 200 { count: number }
*/
notificationRouter.get(
'/unread-count',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req);
const count = await Notification.countDocuments({ user: userId, isRead: false });
res.json({ count });
}),
);
/**
* PATCH /api/notifications/:id/read
* Помечает одно уведомление как прочитанное.
*
* @returns 200 { notification: { ... } }
*/
notificationRouter.patch(
'/:id/read',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req);
const notification = await Notification.findOne({ _id: req.params.id, user: userId });
if (!notification) {
throw new ApiError(404, 'NOTIFICATION_NOT_FOUND', 'Уведомление не найдено');
}
notification.isRead = true;
await notification.save();
res.json({ notification: serializeNotification(notification) });
}),
);
/**
* POST /api/notifications/read-all
* Помечает все уведомления как прочитанные.
*
* @returns 200 { count: number } — количество помеченных
*/
notificationRouter.post(
'/read-all',
asyncHandler(async (req: Request, res: Response) => {
const userId = getUserId(req);
const result = await Notification.updateMany(
{ user: userId, isRead: false },
{ $set: { isRead: true } },
);
res.json({ count: result.modifiedCount });
}),
);
export default notificationRouter;
+15 -3
View File
@@ -4,6 +4,7 @@ import { createApp } from './app.js';
import { connectDatabase } from './config/database.js'; import { connectDatabase } from './config/database.js';
import { env } from './config/env.js'; import { env } from './config/env.js';
import { startPublicationScheduler, stopPublicationScheduler } from './services/publicationScheduler.service.js'; import { startPublicationScheduler, stopPublicationScheduler } from './services/publicationScheduler.service.js';
import { createSocketServer } from './socket/socketServer.js';
/** /**
* Завершает работу процесса после закрытия сервера. * Завершает работу процесса после закрытия сервера.
@@ -22,13 +23,24 @@ function shutdown(signal: string, server: http.Server): void {
/** /**
* Точка входа приложения. * Точка входа приложения.
* *
* Подключает MongoDB и запускает HTTP-сервер на порту из env. * Подключает MongoDB, создаёт HTTP-сервер, Socket.IO и Express, запускает scheduler.
*
* Socket.IO подключается к HTTP-серверу через engine.io (перехватывает /socket.io).
* Express не отвечает на /socket.io (middleware в app.ts) — Socket.IO обрабатывает.
*/ */
async function main(): Promise<void> { async function main(): Promise<void> {
await connectDatabase(); await connectDatabase();
const app = createApp(); // Создаём HTTP-сервер (без handler — добавим через server.on)
const server = http.createServer(app); const server = http.createServer();
// Socket.IO подключается к HTTP-серверу (engine.io перехватывает /socket.io)
const io = createSocketServer(server);
// Express-приложение (с io для news routes)
// Express НЕ отвечает на /socket.io — middleware в app.ts
const app = createApp({ io });
server.on('request', app);
// Запускаем планировщик отложенной публикации // Запускаем планировщик отложенной публикации
startPublicationScheduler(env.schedulerIntervalMs); startPublicationScheduler(env.schedulerIntervalMs);
@@ -0,0 +1,78 @@
import Notification from '../models/notification.model.js';
import type { NotificationType } from '../models/notification.model.js';
import type { Server as SocketIOServer } from 'socket.io';
/** Параметры для создания уведомления. */
interface CreateNotificationParams {
/** Пользователь-получатель. */
user: string;
/** Пользователь-инициатор действия. */
actor: string;
/** Тип события. */
type: NotificationType;
/** Id новости (если применимо). */
newsId?: string;
/** Заголовок. */
title: string;
/** Сообщение. */
message: string;
}
/**
* Сохраняет уведомление в БД и отправляет real-time событие через Socket.IO.
*
* @param io — экземпляр Socket.IO server
* @param params — данные уведомления
* @returns сохранённое уведомление (или null, если получатель = автор — не уведомляем себя)
*/
export async function createNotification(
io: SocketIOServer,
params: CreateNotificationParams,
): Promise<void> {
// Не уведомляем пользователя о собственных действиях
if (params.user === params.actor) {
return;
}
const notification = await Notification.create({
user: params.user,
actor: params.actor,
type: params.type,
news: params.newsId ?? null,
title: params.title,
message: params.message,
isRead: false,
});
// Отправляем real-time событие в room получателя
io.to(`user:${params.user}`).emit('notification', {
id: notification._id,
type: notification.type,
news: notification.news,
title: notification.title,
message: notification.message,
isRead: false,
createdAt: notification.createdAt,
});
}
/**
* Публикует событие в room пользователя (без сохранения в БД).
*
* Используется для событий, которые не являются "уведомлениями"
* в классическом смысле (например, обновление списка в реальном времени).
*
* @param io — экземпляр Socket.IO server
* @param userId — получатель
* @param event — название события
* @param data — payload
*/
export function emitToUser(
io: SocketIOServer,
userId: string,
event: string,
data: unknown,
): void {
io.to(`user:${userId}`).emit(event, data);
}
+13
View File
@@ -0,0 +1,13 @@
/**
* Расширение типов Socket.IO для хранения userId в socket.data.
*/
import type { Socket } from 'socket.io';
declare module 'socket.io' {
interface Socket {
/** Id авторизованного пользователя (устанавливается middleware). */
userId: string;
}
}
export type { Socket };
+46
View File
@@ -0,0 +1,46 @@
import { Server } from 'socket.io';
import { env } from '../config/env.js';
import { verifyUserToken } from '../utils/jwt.js';
import type { Server as HttpServer } from 'node:http';
import type { Server as IOServer } from 'socket.io';
/**
* Создаёт и настраивает Socket.IO сервер.
*
* @param httpServer — HTTP-сервер Express
* @returns настроенный Socket.IO server
*/
export function createSocketServer(httpServer: HttpServer): IOServer {
const io = new Server(httpServer, {
cors: { origin: env.clientOrigins },
});
// Middleware аутентификации: проверяем JWT из handshake.auth.token
io.use((socket, next) => {
// handshake.auth — any в типах socket.io, извлекаем token
const token: unknown = socket.handshake.auth.token;
if (typeof token !== 'string' || token.length === 0) {
next(new Error('UNAUTHORIZED: отсутствует токен'));
return;
}
try {
const payload = verifyUserToken(token);
// eslint-disable-next-line no-param-reassign -- socket.userId — стандартный паттерн Socket.IO
socket.userId = payload.id;
next();
} catch {
next(new Error('UNAUTHORIZED: недействительный токен'));
}
});
// При подключении — добавляем socket в room пользователя
io.on('connection', (socket) => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises -- socket.join fire-and-forget
void socket.join(`user:${socket.userId}`);
});
return io;
}
+2 -2
View File
@@ -68,7 +68,7 @@ describe('API skeleton', () => {
describe('error middleware', () => { describe('error middleware', () => {
it('обрабатывает ApiError с её статусом и кодом', async () => { it('обрабатывает ApiError с её статусом и кодом', async () => {
const errorApp = createApp(throwingMiddleware('/api/test-conflict', new ApiError(409, 'CONFLICT', 'Тестовый конфликт'))); const errorApp = createApp({ extraMiddleware: throwingMiddleware('/api/test-conflict', new ApiError(409, 'CONFLICT', 'Тестовый конфликт')) });
const res = await request(errorApp).get('/api/test-conflict'); const res = await request(errorApp).get('/api/test-conflict');
expect(res.status).toBe(409); expect(res.status).toBe(409);
@@ -76,7 +76,7 @@ describe('API skeleton', () => {
}); });
it('возвращает 500 для непредвиденных ошибок', async () => { it('возвращает 500 для непредвиденных ошибок', async () => {
const errorApp = createApp(throwingMiddleware('/api/test-unexpected', new Error('Внутренний сбой'))); const errorApp = createApp({ extraMiddleware: throwingMiddleware('/api/test-unexpected', new Error('Внутренний сбой')) });
const res = await request(errorApp).get('/api/test-unexpected'); const res = await request(errorApp).get('/api/test-unexpected');
expect(res.status).toBe(500); expect(res.status).toBe(500);