feat: Добавлена базовая структура приложения Home Service с бэкендом на NestJS и фронтендом на Next.js для управления событиями.
This commit is contained in:
43
.gitignore
vendored
Normal file
43
.gitignore
vendored
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
# Dependencies
|
||||||
|
node_modules/
|
||||||
|
.pnp
|
||||||
|
.pnp.js
|
||||||
|
|
||||||
|
# Turborepo
|
||||||
|
.turbo
|
||||||
|
|
||||||
|
# Build outputs
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
.next/
|
||||||
|
out/
|
||||||
|
|
||||||
|
# Environment
|
||||||
|
.env
|
||||||
|
.env*.local
|
||||||
|
|
||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# IDEs
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*~
|
||||||
|
|
||||||
|
# Testing
|
||||||
|
coverage/
|
||||||
|
.nyc_output/
|
||||||
|
|
||||||
|
# Misc
|
||||||
|
*.tsbuildinfo
|
||||||
245
README.md
245
README.md
@@ -1,2 +1,247 @@
|
|||||||
# home-service
|
# home-service
|
||||||
|
|
||||||
|
Современный монорепозиторий для сервиса домашней автоматизации с бэкендом и админ-панелью.
|
||||||
|
|
||||||
|
## 🚀 Стек технологий
|
||||||
|
|
||||||
|
**Инфраструктура:**
|
||||||
|
- Turborepo - система сборки монорепозитория
|
||||||
|
- pnpm Workspaces - управление зависимостями
|
||||||
|
|
||||||
|
**Backend:**
|
||||||
|
- NestJS 10
|
||||||
|
- PGLite (встроенная PostgreSQL БД)
|
||||||
|
- Drizzle ORM
|
||||||
|
- Zod для валидации
|
||||||
|
- date-fns для работы с датами
|
||||||
|
|
||||||
|
**Admin:**
|
||||||
|
- Next.js 16 (App Router)
|
||||||
|
- React 19
|
||||||
|
- TailwindCSS 4
|
||||||
|
- TypeScript
|
||||||
|
|
||||||
|
## 📁 Структура проекта
|
||||||
|
|
||||||
|
```
|
||||||
|
home-service/
|
||||||
|
├── backend/ # NestJS API (@home-service/backend)
|
||||||
|
│ ├── src/
|
||||||
|
│ │ ├── database/ # Схема БД и модуль
|
||||||
|
│ │ ├── events/ # Модуль событий
|
||||||
|
│ │ ├── utils/ # Утилиты для дат
|
||||||
|
│ │ └── pipes/ # Zod validation pipe
|
||||||
|
│ ├── migrations/ # Миграции БД
|
||||||
|
│ └── data/ # База данных PGLite
|
||||||
|
│
|
||||||
|
├── admin/ # Next.js админка (@home-service/admin)
|
||||||
|
│ └── src/
|
||||||
|
│ ├── app/ # Страницы
|
||||||
|
│ ├── components/ # React компоненты
|
||||||
|
│ └── lib/ # API клиент
|
||||||
|
│
|
||||||
|
├── turbo.json # Конфигурация Turborepo
|
||||||
|
├── pnpm-workspace.yaml # Конфигурация pnpm workspaces
|
||||||
|
└── package.json # Корневой package.json
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🎯 Типы событий
|
||||||
|
|
||||||
|
База данных поддерживает три типа событий. Тип определяется автоматически по заполненным полям:
|
||||||
|
|
||||||
|
1. **recurring** - Обычное повторяющееся событие
|
||||||
|
- Поля: `month`, `day`
|
||||||
|
- Пример: Новый год, 8 марта
|
||||||
|
|
||||||
|
2. **anniversary** - Годовщина с отслеживанием времени
|
||||||
|
- Поля: `month`, `day`, `startYear`
|
||||||
|
- Пример: день рождения, свадьба
|
||||||
|
|
||||||
|
3. **duration** - Продолжительное событие
|
||||||
|
- Поля: `month`, `day`, `startYear`, `endMonth`, `endDay`, `endYear`
|
||||||
|
- Пример: отпуск, командировка
|
||||||
|
|
||||||
|
## ⚡ Быстрый старт
|
||||||
|
|
||||||
|
### Требования
|
||||||
|
- Node.js 20+
|
||||||
|
- pnpm 9+
|
||||||
|
|
||||||
|
### Установка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Установить pnpm глобально (если еще не установлен)
|
||||||
|
npm install -g pnpm
|
||||||
|
|
||||||
|
# Установить все зависимости для всех пакетов
|
||||||
|
pnpm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### Разработка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Запустить все приложения в режиме разработки
|
||||||
|
pnpm dev
|
||||||
|
|
||||||
|
# Запустить только backend
|
||||||
|
pnpm --filter @home-service/backend dev
|
||||||
|
|
||||||
|
# Запустить только admin
|
||||||
|
pnpm --filter @home-service/admin dev
|
||||||
|
```
|
||||||
|
|
||||||
|
**Адреса:**
|
||||||
|
- Backend API: `http://localhost:3000`
|
||||||
|
- Admin панель: `http://localhost:3001`
|
||||||
|
|
||||||
|
### Сборка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Собрать все приложения (с кешированием через Turborepo)
|
||||||
|
pnpm build
|
||||||
|
|
||||||
|
# Собрать только backend
|
||||||
|
pnpm --filter @home-service/backend build
|
||||||
|
|
||||||
|
# Собрать только admin
|
||||||
|
pnpm --filter @home-service/admin build
|
||||||
|
```
|
||||||
|
|
||||||
|
### Другие команды
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Линтинг всех пакетов
|
||||||
|
pnpm lint
|
||||||
|
|
||||||
|
# Форматирование (для backend с Biome)
|
||||||
|
pnpm format
|
||||||
|
|
||||||
|
# Тестирование
|
||||||
|
pnpm test
|
||||||
|
|
||||||
|
# Очистка всех node_modules и кеша
|
||||||
|
pnpm clean
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### GET /countdown
|
||||||
|
Главный endpoint для виджета Glance. Возвращает все события с расчетами.
|
||||||
|
|
||||||
|
**Ответ:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"events": [
|
||||||
|
{
|
||||||
|
"id": "uuid",
|
||||||
|
"type": "recurring",
|
||||||
|
"emoji": "🎄",
|
||||||
|
"name": "Новый год",
|
||||||
|
"date": "2026-01-01",
|
||||||
|
"display": "365д 5ч 36м",
|
||||||
|
"days": 365,
|
||||||
|
"hours": 5,
|
||||||
|
"minutes": 36
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"current": {
|
||||||
|
"year": 2025,
|
||||||
|
"month": 11,
|
||||||
|
"day": 29
|
||||||
|
},
|
||||||
|
"months": [...],
|
||||||
|
"timelineGrid": [...]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### GET /api/events
|
||||||
|
Получить все события
|
||||||
|
|
||||||
|
### POST /api/events
|
||||||
|
Создать новое событие
|
||||||
|
|
||||||
|
**Body:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"title": "День рождения",
|
||||||
|
"emoji": "🎂",
|
||||||
|
"month": 6,
|
||||||
|
"day": 15,
|
||||||
|
"startYear": 1990
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### DELETE /api/events/:id
|
||||||
|
Удалить событие
|
||||||
|
|
||||||
|
## Конфигурация
|
||||||
|
|
||||||
|
### Backend (.env)
|
||||||
|
```
|
||||||
|
PORT=3000
|
||||||
|
CORS_ORIGIN=http://localhost:3001
|
||||||
|
DATABASE_PATH=./data/events.db
|
||||||
|
```
|
||||||
|
|
||||||
|
### Admin (.env.local)
|
||||||
|
```
|
||||||
|
NEXT_PUBLIC_API_URL=http://localhost:3000
|
||||||
|
```
|
||||||
|
|
||||||
|
## Миграция данных
|
||||||
|
|
||||||
|
Для импорта событий из старого Python бэкенда можно использовать API:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Пример импорта события
|
||||||
|
curl -X POST http://localhost:3000/api/events \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"title":"Новый год","emoji":"🎄","month":1,"day":1}'
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🚢 Production
|
||||||
|
|
||||||
|
### Все приложения
|
||||||
|
```bash
|
||||||
|
pnpm build
|
||||||
|
pnpm --filter @home-service/backend start:prod
|
||||||
|
pnpm --filter @home-service/admin start
|
||||||
|
```
|
||||||
|
|
||||||
|
### Backend отдельно
|
||||||
|
```bash
|
||||||
|
pnpm --filter @home-service/backend build
|
||||||
|
pnpm --filter @home-service/backend start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
### Admin отдельно
|
||||||
|
```bash
|
||||||
|
pnpm --filter @home-service/admin build
|
||||||
|
pnpm --filter @home-service/admin start
|
||||||
|
```
|
||||||
|
|
||||||
|
## 🛠️ Разработка
|
||||||
|
|
||||||
|
### Создание миграции
|
||||||
|
```bash
|
||||||
|
pnpm --filter @home-service/backend exec drizzle-kit generate
|
||||||
|
```
|
||||||
|
|
||||||
|
### Применение миграций
|
||||||
|
Миграции применяются автоматически при старте приложения.
|
||||||
|
|
||||||
|
### Работа с Turborepo
|
||||||
|
|
||||||
|
**Кеширование:**
|
||||||
|
Turborepo автоматически кеширует результаты сборок. При повторном запуске `pnpm build` без изменений файлов, сборка завершится мгновенно.
|
||||||
|
|
||||||
|
**Очистка кеша:**
|
||||||
|
```bash
|
||||||
|
rm -rf .turbo
|
||||||
|
# или
|
||||||
|
pnpm clean
|
||||||
|
```
|
||||||
|
|
||||||
|
## Лицензия
|
||||||
|
|
||||||
|
MIT
|
||||||
|
|||||||
41
admin/.gitignore
vendored
Normal file
41
admin/.gitignore
vendored
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||||
|
|
||||||
|
# dependencies
|
||||||
|
/node_modules
|
||||||
|
/.pnp
|
||||||
|
.pnp.*
|
||||||
|
.yarn/*
|
||||||
|
!.yarn/patches
|
||||||
|
!.yarn/plugins
|
||||||
|
!.yarn/releases
|
||||||
|
!.yarn/versions
|
||||||
|
|
||||||
|
# testing
|
||||||
|
/coverage
|
||||||
|
|
||||||
|
# next.js
|
||||||
|
/.next/
|
||||||
|
/out/
|
||||||
|
|
||||||
|
# production
|
||||||
|
/build
|
||||||
|
|
||||||
|
# misc
|
||||||
|
.DS_Store
|
||||||
|
*.pem
|
||||||
|
|
||||||
|
# debug
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
.pnpm-debug.log*
|
||||||
|
|
||||||
|
# env files (can opt-in for committing if needed)
|
||||||
|
.env*
|
||||||
|
|
||||||
|
# vercel
|
||||||
|
.vercel
|
||||||
|
|
||||||
|
# typescript
|
||||||
|
*.tsbuildinfo
|
||||||
|
next-env.d.ts
|
||||||
36
admin/README.md
Normal file
36
admin/README.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
First, run the development server:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
# or
|
||||||
|
yarn dev
|
||||||
|
# or
|
||||||
|
pnpm dev
|
||||||
|
# or
|
||||||
|
bun dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
|
||||||
|
|
||||||
|
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
|
||||||
|
|
||||||
|
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
|
||||||
|
|
||||||
|
## Learn More
|
||||||
|
|
||||||
|
To learn more about Next.js, take a look at the following resources:
|
||||||
|
|
||||||
|
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
|
||||||
|
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
|
||||||
|
|
||||||
|
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
|
||||||
|
|
||||||
|
## Deploy on Vercel
|
||||||
|
|
||||||
|
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
|
||||||
|
|
||||||
|
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
|
||||||
18
admin/eslint.config.mjs
Normal file
18
admin/eslint.config.mjs
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { defineConfig, globalIgnores } from "eslint/config";
|
||||||
|
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||||
|
import nextTs from "eslint-config-next/typescript";
|
||||||
|
|
||||||
|
const eslintConfig = defineConfig([
|
||||||
|
...nextVitals,
|
||||||
|
...nextTs,
|
||||||
|
// Override default ignores of eslint-config-next.
|
||||||
|
globalIgnores([
|
||||||
|
// Default ignores of eslint-config-next:
|
||||||
|
".next/**",
|
||||||
|
"out/**",
|
||||||
|
"build/**",
|
||||||
|
"next-env.d.ts",
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
export default eslintConfig;
|
||||||
7
admin/next.config.ts
Normal file
7
admin/next.config.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
|
const nextConfig: NextConfig = {
|
||||||
|
/* config options here */
|
||||||
|
};
|
||||||
|
|
||||||
|
export default nextConfig;
|
||||||
26
admin/package.json
Normal file
26
admin/package.json
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"name": "@home-service/admin",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev",
|
||||||
|
"build": "next build",
|
||||||
|
"start": "next start",
|
||||||
|
"lint": "eslint"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"next": "16.0.5",
|
||||||
|
"react": "19.2.0",
|
||||||
|
"react-dom": "19.2.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@tailwindcss/postcss": "^4",
|
||||||
|
"@types/node": "^20",
|
||||||
|
"@types/react": "^19",
|
||||||
|
"@types/react-dom": "^19",
|
||||||
|
"eslint": "^9",
|
||||||
|
"eslint-config-next": "16.0.5",
|
||||||
|
"tailwindcss": "^4",
|
||||||
|
"typescript": "^5"
|
||||||
|
}
|
||||||
|
}
|
||||||
4013
admin/pnpm-lock.yaml
generated
Normal file
4013
admin/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
7
admin/postcss.config.mjs
Normal file
7
admin/postcss.config.mjs
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
const config = {
|
||||||
|
plugins: {
|
||||||
|
"@tailwindcss/postcss": {},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default config;
|
||||||
1
admin/public/file.svg
Normal file
1
admin/public/file.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>
|
||||||
|
After Width: | Height: | Size: 391 B |
1
admin/public/globe.svg
Normal file
1
admin/public/globe.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>
|
||||||
|
After Width: | Height: | Size: 1.0 KiB |
1
admin/public/next.svg
Normal file
1
admin/public/next.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
|
||||||
|
After Width: | Height: | Size: 1.3 KiB |
1
admin/public/vercel.svg
Normal file
1
admin/public/vercel.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>
|
||||||
|
After Width: | Height: | Size: 128 B |
1
admin/public/window.svg
Normal file
1
admin/public/window.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>
|
||||||
|
After Width: | Height: | Size: 385 B |
BIN
admin/src/app/favicon.ico
Normal file
BIN
admin/src/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
26
admin/src/app/globals.css
Normal file
26
admin/src/app/globals.css
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
@import "tailwindcss";
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--background: #ffffff;
|
||||||
|
--foreground: #171717;
|
||||||
|
}
|
||||||
|
|
||||||
|
@theme inline {
|
||||||
|
--color-background: var(--background);
|
||||||
|
--color-foreground: var(--foreground);
|
||||||
|
--font-sans: var(--font-geist-sans);
|
||||||
|
--font-mono: var(--font-geist-mono);
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
--background: #0a0a0a;
|
||||||
|
--foreground: #ededed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
background: var(--background);
|
||||||
|
color: var(--foreground);
|
||||||
|
font-family: Arial, Helvetica, sans-serif;
|
||||||
|
}
|
||||||
27
admin/src/app/layout.tsx
Normal file
27
admin/src/app/layout.tsx
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import type { Metadata } from 'next';
|
||||||
|
import { JetBrains_Mono } from 'next/font/google';
|
||||||
|
import './globals.css';
|
||||||
|
|
||||||
|
const jetbrainsMono = JetBrains_Mono({
|
||||||
|
subsets: ['latin', 'cyrillic'],
|
||||||
|
variable: '--font-jetbrains-mono',
|
||||||
|
});
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: 'Администрирование событий',
|
||||||
|
description: 'Управление событиями для виджета Glance',
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RootLayout({
|
||||||
|
children,
|
||||||
|
}: Readonly<{
|
||||||
|
children: React.ReactNode;
|
||||||
|
}>) {
|
||||||
|
return (
|
||||||
|
<html lang="ru">
|
||||||
|
<body className={`${jetbrainsMono.variable} font-mono antialiased`}>
|
||||||
|
{children}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
87
admin/src/app/page.tsx
Normal file
87
admin/src/app/page.tsx
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { api, Event } from '@/lib/api';
|
||||||
|
import { EventForm } from '@/components/EventForm';
|
||||||
|
import { EventList } from '@/components/EventList';
|
||||||
|
import { Timeline } from '@/components/Timeline';
|
||||||
|
|
||||||
|
export default function Home() {
|
||||||
|
const [events, setEvents] = useState<Event[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
|
const loadEvents = async () => {
|
||||||
|
try {
|
||||||
|
const data = await api.getAllEvents();
|
||||||
|
setEvents(data);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to load events:', error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadEvents();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleEventCreated = () => {
|
||||||
|
loadEvents();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEventDeleted = () => {
|
||||||
|
loadEvents();
|
||||||
|
};
|
||||||
|
|
||||||
|
const recurringEvents = events.filter(
|
||||||
|
(e) => !e.startYear && !e.endYear
|
||||||
|
);
|
||||||
|
|
||||||
|
const anniversaryEvents = events.filter(
|
||||||
|
(e) => e.startYear && !e.endYear
|
||||||
|
);
|
||||||
|
|
||||||
|
const durationEvents = events.filter(
|
||||||
|
(e) => e.startYear && e.endYear
|
||||||
|
);
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-950 flex items-center justify-center">
|
||||||
|
<div className="text-gray-400">Загрузка...</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-gray-950 text-gray-300 p-8">
|
||||||
|
<div className="max-w-4xl mx-auto">
|
||||||
|
<h1 className="text-4xl font-bold text-center mb-8 text-white">
|
||||||
|
📅 Управление событиями
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<Timeline />
|
||||||
|
|
||||||
|
<EventForm onEventCreated={handleEventCreated} />
|
||||||
|
|
||||||
|
<EventList
|
||||||
|
title="🎉 Праздники"
|
||||||
|
events={recurringEvents}
|
||||||
|
onEventDeleted={handleEventDeleted}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<EventList
|
||||||
|
title="💍 Годовщины"
|
||||||
|
events={anniversaryEvents}
|
||||||
|
onEventDeleted={handleEventDeleted}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<EventList
|
||||||
|
title="📆 Продолжительные события"
|
||||||
|
events={durationEvents}
|
||||||
|
onEventDeleted={handleEventDeleted}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
266
admin/src/components/EventForm.tsx
Normal file
266
admin/src/components/EventForm.tsx
Normal file
@@ -0,0 +1,266 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { api, CreateEventInput } from '@/lib/api';
|
||||||
|
|
||||||
|
type EventType = 'recurring' | 'anniversary' | 'duration';
|
||||||
|
|
||||||
|
interface EventFormProps {
|
||||||
|
onEventCreated: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EventForm({ onEventCreated }: EventFormProps) {
|
||||||
|
const [eventType, setEventType] = useState<EventType>('recurring');
|
||||||
|
const [formData, setFormData] = useState<CreateEventInput>({
|
||||||
|
title: '',
|
||||||
|
emoji: '',
|
||||||
|
month: 1,
|
||||||
|
day: 1,
|
||||||
|
});
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setSubmitting(true);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await api.createEvent(formData);
|
||||||
|
setFormData({
|
||||||
|
title: '',
|
||||||
|
emoji: '',
|
||||||
|
month: 1,
|
||||||
|
day: 1,
|
||||||
|
});
|
||||||
|
onEventCreated();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to create event:', error);
|
||||||
|
alert('Не удалось создать событие');
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-gray-900 rounded-xl p-6 mb-8 shadow-xl">
|
||||||
|
<h2 className="text-2xl font-bold mb-6 text-white">Добавить событие</h2>
|
||||||
|
|
||||||
|
<div className="flex gap-3 mb-6">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setEventType('recurring');
|
||||||
|
setFormData({ ...formData, startYear: undefined, endYear: undefined, endMonth: undefined, endDay: undefined });
|
||||||
|
}}
|
||||||
|
className={`px-4 py-2 rounded-lg font-medium transition-colors ${
|
||||||
|
eventType === 'recurring'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-400 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Праздник (ежегодно)
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setEventType('anniversary');
|
||||||
|
setFormData({ ...formData, endYear: undefined, endMonth: undefined, endDay: undefined });
|
||||||
|
}}
|
||||||
|
className={`px-4 py-2 rounded-lg font-medium transition-colors ${
|
||||||
|
eventType === 'anniversary'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-400 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Годовщина (с годом)
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setEventType('duration')}
|
||||||
|
className={`px-4 py-2 rounded-lg font-medium transition-colors ${
|
||||||
|
eventType === 'duration'
|
||||||
|
? 'bg-blue-600 text-white'
|
||||||
|
: 'bg-gray-800 text-gray-400 hover:bg-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Продолжительное
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="col-span-2">
|
||||||
|
<label className="block text-sm font-medium mb-2">Название</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={formData.title}
|
||||||
|
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-white focus:border-blue-500 focus:outline-none"
|
||||||
|
placeholder="Например: День рождения"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">Эмодзи</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={formData.emoji}
|
||||||
|
onChange={(e) => setFormData({ ...formData, emoji: e.target.value })}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-white text-2xl focus:border-blue-500 focus:outline-none"
|
||||||
|
placeholder="🎂"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(eventType === 'anniversary' || eventType === 'duration') && (
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">Год начала</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
required={eventType !== 'recurring'}
|
||||||
|
value={formData.startYear || ''}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
startYear: e.target.value ? parseInt(e.target.value) : undefined,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-white focus:border-blue-500 focus:outline-none"
|
||||||
|
placeholder="2023"
|
||||||
|
min="1900"
|
||||||
|
max="2100"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">Месяц</label>
|
||||||
|
<select
|
||||||
|
required
|
||||||
|
value={formData.month}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData({ ...formData, month: parseInt(e.target.value) })
|
||||||
|
}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-white focus:border-blue-500 focus:outline-none"
|
||||||
|
>
|
||||||
|
{[
|
||||||
|
'Январь',
|
||||||
|
'Февраль',
|
||||||
|
'Март',
|
||||||
|
'Апрель',
|
||||||
|
'Май',
|
||||||
|
'Июнь',
|
||||||
|
'Июль',
|
||||||
|
'Август',
|
||||||
|
'Сентябрь',
|
||||||
|
'Октябрь',
|
||||||
|
'Ноябрь',
|
||||||
|
'Декабрь',
|
||||||
|
].map((month, index) => (
|
||||||
|
<option key={index} value={index + 1}>
|
||||||
|
{month}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">День</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
required
|
||||||
|
value={formData.day}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData({ ...formData, day: parseInt(e.target.value) })
|
||||||
|
}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-white focus:border-blue-500 focus:outline-none"
|
||||||
|
min="1"
|
||||||
|
max="31"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{eventType === 'duration' && (
|
||||||
|
<>
|
||||||
|
<div className="col-span-2 border-t border-gray-800 pt-4 mt-2">
|
||||||
|
<h3 className="text-lg font-medium mb-4 text-white">Дата окончания</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">Год окончания</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
required={eventType === 'duration'}
|
||||||
|
value={formData.endYear || ''}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData({
|
||||||
|
...formData,
|
||||||
|
endYear: e.target.value ? parseInt(e.target.value) : undefined,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-white focus:border-blue-500 focus:outline-none"
|
||||||
|
placeholder="2024"
|
||||||
|
min="1900"
|
||||||
|
max="2100"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">Месяц окончания</label>
|
||||||
|
<select
|
||||||
|
required={eventType === 'duration'}
|
||||||
|
value={formData.endMonth || 1}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData({ ...formData, endMonth: parseInt(e.target.value) })
|
||||||
|
}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-white focus:border-blue-500 focus:outline-none"
|
||||||
|
>
|
||||||
|
{[
|
||||||
|
'Январь',
|
||||||
|
'Февраль',
|
||||||
|
'Март',
|
||||||
|
'Апрель',
|
||||||
|
'Май',
|
||||||
|
'Июнь',
|
||||||
|
'Июль',
|
||||||
|
'Август',
|
||||||
|
'Сентябрь',
|
||||||
|
'Октябрь',
|
||||||
|
'Ноябрь',
|
||||||
|
'Декабрь',
|
||||||
|
].map((month, index) => (
|
||||||
|
<option key={index} value={index + 1}>
|
||||||
|
{month}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium mb-2">День окончания</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
required={eventType === 'duration'}
|
||||||
|
value={formData.endDay || ''}
|
||||||
|
onChange={(e) =>
|
||||||
|
setFormData({ ...formData, endDay: parseInt(e.target.value) })
|
||||||
|
}
|
||||||
|
className="w-full bg-gray-800 border border-gray-700 rounded-lg px-4 py-2 text-white focus:border-blue-500 focus:outline-none"
|
||||||
|
min="1"
|
||||||
|
max="31"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="col-span-2">
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={submitting}
|
||||||
|
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
{submitting ? 'Добавление...' : 'Добавить'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
74
admin/src/components/EventList.tsx
Normal file
74
admin/src/components/EventList.tsx
Normal file
@@ -0,0 +1,74 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { api, Event } from '@/lib/api';
|
||||||
|
|
||||||
|
interface EventListProps {
|
||||||
|
title: string;
|
||||||
|
events: Event[];
|
||||||
|
onEventDeleted: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EventList({ title, events, onEventDeleted }: EventListProps) {
|
||||||
|
const [deleting, setDeleting] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const handleDelete = async (id: string) => {
|
||||||
|
if (!confirm('Вы уверены? Это действие нельзя отменить.')) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setDeleting(id);
|
||||||
|
try {
|
||||||
|
await api.deleteEvent(id);
|
||||||
|
onEventDeleted();
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to delete event:', error);
|
||||||
|
alert('Не удалось удалить событие');
|
||||||
|
} finally {
|
||||||
|
setDeleting(null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatDate = (event: Event) => {
|
||||||
|
if (event.endYear) {
|
||||||
|
return `${event.day}.${event.month}.${event.startYear} - ${event.endDay}.${event.endMonth}.${event.endYear}`;
|
||||||
|
}
|
||||||
|
if (event.startYear) {
|
||||||
|
return `${event.day}.${event.month}.${event.startYear}`;
|
||||||
|
}
|
||||||
|
return `${event.day}.${event.month}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (events.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-gray-900 rounded-xl p-6 mb-6 shadow-xl">
|
||||||
|
<h2 className="text-2xl font-bold mb-4 text-white">{title}</h2>
|
||||||
|
<ul className="space-y-2">
|
||||||
|
{events.map((event) => (
|
||||||
|
<li
|
||||||
|
key={event.id}
|
||||||
|
className="flex items-center justify-between p-3 bg-gray-800 rounded-lg hover:bg-gray-750 transition-colors"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className="text-3xl">{event.emoji}</span>
|
||||||
|
<div>
|
||||||
|
<div className="text-white font-medium">{event.title}</div>
|
||||||
|
<div className="text-sm text-gray-400">{formatDate(event)}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(event.id)}
|
||||||
|
disabled={deleting === event.id}
|
||||||
|
className="px-3 py-1 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
|
>
|
||||||
|
{deleting === event.id ? 'Удаление...' : 'Удалить'}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
491
admin/src/components/Timeline.tsx
Normal file
491
admin/src/components/Timeline.tsx
Normal file
@@ -0,0 +1,491 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useEffect, useState, useRef } from 'react';
|
||||||
|
import { api } from '@/lib/api';
|
||||||
|
|
||||||
|
interface TimelineEvent {
|
||||||
|
id: string;
|
||||||
|
type: string;
|
||||||
|
emoji: string;
|
||||||
|
name: string;
|
||||||
|
date: string;
|
||||||
|
display: string;
|
||||||
|
days: number;
|
||||||
|
hours: number;
|
||||||
|
minutes: number;
|
||||||
|
yearsPassed?: number;
|
||||||
|
daysPassed?: number;
|
||||||
|
startYear?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TimelineGridItem {
|
||||||
|
days: number;
|
||||||
|
date: string;
|
||||||
|
weekday: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MonthMarker {
|
||||||
|
name: string;
|
||||||
|
days: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Timeline() {
|
||||||
|
const [events, setEvents] = useState<TimelineEvent[]>([]);
|
||||||
|
const [timelineGrid, setTimelineGrid] = useState<TimelineGridItem[]>([]);
|
||||||
|
const [months, setMonths] = useState<MonthMarker[]>([]);
|
||||||
|
const [hoveredGrid, setHoveredGrid] = useState<number | null>(null);
|
||||||
|
const [hoveredEvent, setHoveredEvent] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const timelineRef = useRef<HTMLDivElement>(null);
|
||||||
|
const eventRefs = useRef<Map<string, HTMLDivElement>>(new Map());
|
||||||
|
|
||||||
|
const daysInFirstZone = 14;
|
||||||
|
const weeksInSecondZone = 40;
|
||||||
|
const firstZonePercent = 25.0;
|
||||||
|
const secondZonePercent = 75.0;
|
||||||
|
const maxDays = daysInFirstZone + weeksInSecondZone * 7;
|
||||||
|
|
||||||
|
const REPULSION_RADIUS = 80;
|
||||||
|
const REPULSION_STRENGTH = 20;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadCountdownData();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Добавляем эффект отталкивания для эмодзи
|
||||||
|
const timeline = timelineRef.current;
|
||||||
|
if (!timeline) return;
|
||||||
|
|
||||||
|
const eventElements = Array.from(eventRefs.current.values());
|
||||||
|
if (eventElements.length === 0) return;
|
||||||
|
|
||||||
|
// Для каждого элемента добавляем обработчики
|
||||||
|
eventElements.forEach((hoverItem) => {
|
||||||
|
const handleMouseEnter = () => {
|
||||||
|
const hoveredRect = hoverItem.getBoundingClientRect();
|
||||||
|
const timelineRect = timeline.getBoundingClientRect();
|
||||||
|
const hoveredX = hoveredRect.left + hoveredRect.width / 2 - timelineRect.left;
|
||||||
|
const hoveredY = hoveredRect.top + hoveredRect.height / 2 - timelineRect.top;
|
||||||
|
|
||||||
|
// Отталкиваем все остальные элементы
|
||||||
|
eventElements.forEach((item) => {
|
||||||
|
if (item === hoverItem) return;
|
||||||
|
|
||||||
|
const itemRect = item.getBoundingClientRect();
|
||||||
|
const itemX = itemRect.left + itemRect.width / 2 - timelineRect.left;
|
||||||
|
const itemY = itemRect.top + itemRect.height / 2 - timelineRect.top;
|
||||||
|
|
||||||
|
const dx = itemX - hoveredX;
|
||||||
|
const dy = itemY - hoveredY;
|
||||||
|
const distance = Math.sqrt(dx * dx + dy * dy);
|
||||||
|
|
||||||
|
if (distance < REPULSION_RADIUS && distance > 0) {
|
||||||
|
const nx = dx / distance;
|
||||||
|
const ny = dy / distance;
|
||||||
|
const force = (1 - distance / REPULSION_RADIUS) * REPULSION_STRENGTH;
|
||||||
|
|
||||||
|
const offsetX = nx * force;
|
||||||
|
const offsetY = ny * force;
|
||||||
|
|
||||||
|
item.style.transform = `translate(calc(-50% + ${offsetX}px), calc(-50% + ${offsetY}px))`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleMouseLeave = () => {
|
||||||
|
// Возвращаем ВСЕ элементы на свои исходные позиции
|
||||||
|
eventElements.forEach((item) => {
|
||||||
|
item.style.transform = 'translate(-50%, -50%)';
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
hoverItem.addEventListener('mouseenter', handleMouseEnter);
|
||||||
|
hoverItem.addEventListener('mouseleave', handleMouseLeave);
|
||||||
|
|
||||||
|
// Сохраняем обработчики для cleanup
|
||||||
|
(hoverItem as any)._repulsionHandlers = { handleMouseEnter, handleMouseLeave };
|
||||||
|
});
|
||||||
|
|
||||||
|
// Cleanup
|
||||||
|
return () => {
|
||||||
|
eventElements.forEach((element) => {
|
||||||
|
const handlers = (element as any)._repulsionHandlers;
|
||||||
|
if (handlers) {
|
||||||
|
element.removeEventListener('mouseenter', handlers.handleMouseEnter);
|
||||||
|
element.removeEventListener('mouseleave', handlers.handleMouseLeave);
|
||||||
|
delete (element as any)._repulsionHandlers;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}, [events, REPULSION_RADIUS, REPULSION_STRENGTH]); // Пересоздаем обработчики при изменении событий
|
||||||
|
|
||||||
|
const loadCountdownData = async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000'}/countdown`);
|
||||||
|
const data = await response.json();
|
||||||
|
setEvents(data.events || []);
|
||||||
|
setTimelineGrid(data.timelineGrid || []);
|
||||||
|
setMonths(data.months || []);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to load countdown data:', error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const calculatePosition = (days: number): number => {
|
||||||
|
if (days >= maxDays) return 100;
|
||||||
|
|
||||||
|
if (days < daysInFirstZone) {
|
||||||
|
// Зона 1: 0-14 дней -> 0-25% шкалы
|
||||||
|
return (days / daysInFirstZone) * firstZonePercent;
|
||||||
|
} else {
|
||||||
|
// Зона 2: 14+ дней -> 25-100% шкалы
|
||||||
|
const daysAfterZ1 = days - daysInFirstZone;
|
||||||
|
const weeksInZ2 = daysAfterZ1 / 7;
|
||||||
|
const posInZ2 = (weeksInZ2 / weeksInSecondZone) * secondZonePercent;
|
||||||
|
return firstZonePercent + posInZ2;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const calculateGridWidth = (days: number): number => {
|
||||||
|
if (days < daysInFirstZone) {
|
||||||
|
return firstZonePercent / daysInFirstZone;
|
||||||
|
} else {
|
||||||
|
return secondZonePercent / weeksInSecondZone;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getShakeClass = (position: number): string => {
|
||||||
|
if (position <= 5) return 'animate-shake-very-strong';
|
||||||
|
if (position <= 12) return 'animate-shake-strong';
|
||||||
|
if (position <= 18) return 'animate-shake-medium';
|
||||||
|
if (position <= 25) return 'animate-shake-weak';
|
||||||
|
return '';
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatCountdown = (event: TimelineEvent) => {
|
||||||
|
const days = event.days;
|
||||||
|
if (days >= 30) {
|
||||||
|
const months = Math.floor(days / 30);
|
||||||
|
const remainingDays = days % 30;
|
||||||
|
return (
|
||||||
|
<div className="flex gap-3 justify-around">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="text-base font-bold text-pink-400">{months}</div>
|
||||||
|
<div className="text-[9px] opacity-60 mt-0.5">
|
||||||
|
{months === 1 ? 'месяц' : months >= 2 && months <= 4 ? 'месяца' : 'месяцев'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="text-base font-bold text-orange-400">{remainingDays}</div>
|
||||||
|
<div className="text-[9px] opacity-60 mt-0.5">
|
||||||
|
{remainingDays === 1 ? 'день' : remainingDays >= 2 && remainingDays <= 4 ? 'дня' : 'дней'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
return (
|
||||||
|
<div className="flex gap-3 justify-around">
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="text-base font-bold text-pink-400">{days}</div>
|
||||||
|
<div className="text-[9px] opacity-60 mt-0.5">
|
||||||
|
{days === 1 ? 'день' : days >= 2 && days <= 4 ? 'дня' : 'дней'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="text-center">
|
||||||
|
<div className="text-base font-bold text-orange-400">{event.hours}</div>
|
||||||
|
<div className="text-[9px] opacity-60 mt-0.5">
|
||||||
|
{event.hours === 1 ? 'час' : event.hours >= 2 && event.hours <= 4 ? 'часа' : 'часов'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="bg-gray-900 rounded-xl p-6 shadow-xl">
|
||||||
|
<h2 className="text-2xl font-bold mb-6 text-white text-center">📅 Временная шкала</h2>
|
||||||
|
|
||||||
|
<div ref={timelineRef} className="relative h-[140px]">
|
||||||
|
{/* Линия времени - Зона 1 (0-25%) */}
|
||||||
|
<div
|
||||||
|
className="absolute left-0 top-1/2 -translate-y-1/2 h-[3px]"
|
||||||
|
style={{
|
||||||
|
width: '25%',
|
||||||
|
background: 'linear-gradient(to right, rgba(185, 28, 28, 0.4), rgba(128, 128, 128, 0.4))',
|
||||||
|
backgroundImage:
|
||||||
|
'linear-gradient(to right, rgba(185, 28, 28, 0.4), rgba(128, 128, 128, 0.4)), linear-gradient(to right, rgba(180, 180, 180, 0.6) 1px, transparent 1px)',
|
||||||
|
backgroundSize: '100% 100%, calc(100% / 14) 100%',
|
||||||
|
backgroundRepeat: 'no-repeat, repeat-x',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Линия времени - Зона 2 (25-100%) */}
|
||||||
|
<div
|
||||||
|
className="absolute left-[25%] top-1/2 -translate-y-1/2 h-[3px]"
|
||||||
|
style={{
|
||||||
|
width: '75%',
|
||||||
|
backgroundColor: 'transparent',
|
||||||
|
backgroundImage:
|
||||||
|
'linear-gradient(to right, rgba(128,128,128,0.45) 1px, transparent 1px), linear-gradient(to right, rgba(128,128,128,0.75) 1px, transparent 1px)',
|
||||||
|
backgroundSize: 'calc(100% / 40) 100%, calc(100% / 10) 100%',
|
||||||
|
backgroundRepeat: 'repeat-x, repeat-x',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Маркер "Сегодня" */}
|
||||||
|
<div
|
||||||
|
className="absolute left-0 top-1/2 -translate-x-1/2 -translate-y-1/2 text-2xl z-[15]"
|
||||||
|
style={{
|
||||||
|
textShadow: '0 0 8px rgba(255, 100, 0, 0.6)',
|
||||||
|
filter: 'drop-shadow(0 2px 4px rgba(0,0,0,0.3))',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
🔥
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* События */}
|
||||||
|
{events.map((event) => {
|
||||||
|
if (event.days >= maxDays) return null;
|
||||||
|
|
||||||
|
const position = calculatePosition(event.days);
|
||||||
|
const shakeClass = getShakeClass(position);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={event.id}
|
||||||
|
ref={(el) => {
|
||||||
|
if (el) {
|
||||||
|
eventRefs.current.set(event.id, el);
|
||||||
|
} else {
|
||||||
|
eventRefs.current.delete(event.id);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`absolute top-[35%] -translate-x-1/2 -translate-y-1/2 cursor-pointer z-10 transition-all duration-300 ${shakeClass}`}
|
||||||
|
style={{ left: `${position}%` }}
|
||||||
|
onMouseEnter={() => setHoveredEvent(event.id)}
|
||||||
|
onMouseLeave={() => setHoveredEvent(null)}
|
||||||
|
>
|
||||||
|
{/* Emoji */}
|
||||||
|
<div
|
||||||
|
className="text-[28px] transition-transform duration-300"
|
||||||
|
style={{
|
||||||
|
textShadow: '0 0 3px rgba(0,0,0,0.3), 0 2px 4px rgba(0,0,0,0.2)',
|
||||||
|
transform: hoveredEvent === event.id ? 'scale(1.4)' : 'scale(1)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{event.emoji}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tooltip */}
|
||||||
|
{hoveredEvent === event.id && (
|
||||||
|
<div
|
||||||
|
className="absolute bottom-[45px] left-1/2 -translate-x-1/2 min-w-[200px] z-50"
|
||||||
|
style={{
|
||||||
|
background: 'linear-gradient(135deg, rgba(20,20,25,0.98) 0%, rgba(30,30,40,0.98) 100%)',
|
||||||
|
boxShadow: '0 8px 24px rgba(0,0,0,0.4), 0 0 0 1px rgba(255,255,255,0.1)',
|
||||||
|
backdropFilter: 'blur(10px)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="p-3 rounded-lg">
|
||||||
|
{/* Название */}
|
||||||
|
<div className="flex items-center gap-2 mb-2 pb-2 border-b border-white/15">
|
||||||
|
<div className="text-2xl">{event.emoji}</div>
|
||||||
|
<div className="font-bold text-sm text-white">{event.name}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Дата */}
|
||||||
|
<div className="mb-2 flex items-center gap-1.5 text-[11px]">
|
||||||
|
<div className="opacity-70">📅 Дата:</div>
|
||||||
|
<div className="font-semibold text-blue-400">{event.date}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Годовщина */}
|
||||||
|
{event.type === 'anniversary' && event.yearsPassed && (
|
||||||
|
<div className="bg-purple-500/15 p-2 rounded-md mb-2 border-l-2 border-purple-500">
|
||||||
|
<div className="opacity-90 text-[11px] mb-1">🎉 Годовщина</div>
|
||||||
|
<div className="font-bold text-[15px] text-purple-300">
|
||||||
|
{event.yearsPassed}{' '}
|
||||||
|
{event.yearsPassed % 10 === 1 && event.yearsPassed % 100 !== 11
|
||||||
|
? 'год'
|
||||||
|
: event.yearsPassed % 10 >= 2 &&
|
||||||
|
event.yearsPassed % 10 <= 4 &&
|
||||||
|
(event.yearsPassed % 100 < 12 || event.yearsPassed % 100 > 14)
|
||||||
|
? 'года'
|
||||||
|
: 'лет'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Countdown */}
|
||||||
|
<div className="bg-white/8 p-2 rounded-md">
|
||||||
|
<div className="opacity-70 text-[10px] mb-1 uppercase tracking-wider">⏰ Осталось</div>
|
||||||
|
{formatCountdown(event)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Стрелка */}
|
||||||
|
<div
|
||||||
|
className="absolute -bottom-1.5 left-1/2 -translate-x-1/2 w-0 h-0"
|
||||||
|
style={{
|
||||||
|
borderLeft: '6px solid transparent',
|
||||||
|
borderRight: '6px solid transparent',
|
||||||
|
borderTop: '6px solid rgba(20,20,25,0.98)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{/* Интерактивная сетка */}
|
||||||
|
{timelineGrid.map((gridItem, index) => {
|
||||||
|
if (gridItem.days >= maxDays) return null;
|
||||||
|
|
||||||
|
const position = calculatePosition(gridItem.days);
|
||||||
|
const width = calculateGridWidth(gridItem.days);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="absolute top-[35%] -translate-y-1/2 h-10 cursor-pointer z-[5]"
|
||||||
|
style={{ left: `${position}%`, width: `${width}%` }}
|
||||||
|
onMouseEnter={() => setHoveredGrid(index)}
|
||||||
|
onMouseLeave={() => setHoveredGrid(null)}
|
||||||
|
>
|
||||||
|
{/* Grid tooltip */}
|
||||||
|
{hoveredGrid === index && (
|
||||||
|
<div
|
||||||
|
className="absolute bottom-[45px] left-1/2 -translate-x-1/2 z-50"
|
||||||
|
style={{
|
||||||
|
background: 'linear-gradient(135deg, rgba(30,30,40,0.95) 0%, rgba(40,40,50,0.95) 100%)',
|
||||||
|
boxShadow: '0 4px 12px rgba(0,0,0,0.3), 0 0 0 1px rgba(255,255,255,0.08)',
|
||||||
|
backdropFilter: 'blur(8px)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="p-2 rounded-lg">
|
||||||
|
<div className="text-center mb-1 font-semibold text-blue-400 text-[10px] uppercase tracking-wide">
|
||||||
|
{gridItem.weekday}
|
||||||
|
</div>
|
||||||
|
<div className="text-center font-medium text-[13px] whitespace-nowrap">
|
||||||
|
📅 {gridItem.date}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Стрелка */}
|
||||||
|
<div
|
||||||
|
className="absolute -bottom-[5px] left-1/2 -translate-x-1/2 w-0 h-0"
|
||||||
|
style={{
|
||||||
|
borderLeft: '5px solid transparent',
|
||||||
|
borderRight: '5px solid transparent',
|
||||||
|
borderTop: '5px solid rgba(30,30,40,0.95)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
{/* Метки месяцев */}
|
||||||
|
{months.map((month, index) => {
|
||||||
|
if (month.days >= maxDays) return null;
|
||||||
|
|
||||||
|
const position = calculatePosition(month.days);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="absolute top-[65%] -translate-x-1/2 text-[10px] text-gray-500 whitespace-nowrap"
|
||||||
|
style={{ left: `${position}%` }}
|
||||||
|
>
|
||||||
|
{month.name}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<style jsx>{`
|
||||||
|
@keyframes shake-weak {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translate(-50%, -50%) rotate(0deg);
|
||||||
|
}
|
||||||
|
25% {
|
||||||
|
transform: translate(-50%, -50%) rotate(0.5deg);
|
||||||
|
}
|
||||||
|
75% {
|
||||||
|
transform: translate(-50%, -50%) rotate(-0.5deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes shake-medium {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translate(-50%, -50%) rotate(0deg);
|
||||||
|
}
|
||||||
|
25% {
|
||||||
|
transform: translate(-50%, -50%) rotate(1deg);
|
||||||
|
}
|
||||||
|
75% {
|
||||||
|
transform: translate(-50%, -50%) rotate(-1deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes shake-strong {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translate(-50%, -50%) rotate(0deg);
|
||||||
|
}
|
||||||
|
25% {
|
||||||
|
transform: translate(-50%, -50%) rotate(2deg);
|
||||||
|
}
|
||||||
|
75% {
|
||||||
|
transform: translate(-50%, -50%) rotate(-2deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes shake-very-strong {
|
||||||
|
0%,
|
||||||
|
100% {
|
||||||
|
transform: translate(-50%, -50%) rotate(0deg);
|
||||||
|
}
|
||||||
|
10% {
|
||||||
|
transform: translate(-50%, -50%) rotate(3deg);
|
||||||
|
}
|
||||||
|
30% {
|
||||||
|
transform: translate(-50%, -50%) rotate(-3deg);
|
||||||
|
}
|
||||||
|
50% {
|
||||||
|
transform: translate(-50%, -50%) rotate(3deg);
|
||||||
|
}
|
||||||
|
70% {
|
||||||
|
transform: translate(-50%, -50%) rotate(-3deg);
|
||||||
|
}
|
||||||
|
90% {
|
||||||
|
transform: translate(-50%, -50%) rotate(3deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-shake-weak {
|
||||||
|
animation: shake-weak 2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-shake-medium {
|
||||||
|
animation: shake-medium 1.5s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-shake-strong {
|
||||||
|
animation: shake-strong 1s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.animate-shake-very-strong {
|
||||||
|
animation: shake-very-strong 0.5s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
`}</style>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
56
admin/src/lib/api.ts
Normal file
56
admin/src/lib/api.ts
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
|
||||||
|
|
||||||
|
export interface Event {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
emoji: string;
|
||||||
|
month: number;
|
||||||
|
day: number;
|
||||||
|
startYear?: number | null;
|
||||||
|
endMonth?: number | null;
|
||||||
|
endDay?: number | null;
|
||||||
|
endYear?: number | null;
|
||||||
|
description?: string | null;
|
||||||
|
color?: string | null;
|
||||||
|
isActive: boolean;
|
||||||
|
tags?: string[] | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateEventInput {
|
||||||
|
title: string;
|
||||||
|
emoji: string;
|
||||||
|
month: number;
|
||||||
|
day: number;
|
||||||
|
startYear?: number;
|
||||||
|
endMonth?: number;
|
||||||
|
endDay?: number;
|
||||||
|
endYear?: number;
|
||||||
|
description?: string;
|
||||||
|
color?: string;
|
||||||
|
tags?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
async getAllEvents(): Promise<Event[]> {
|
||||||
|
const res = await fetch(`${API_URL}/api/events`);
|
||||||
|
if (!res.ok) throw new Error('Failed to fetch events');
|
||||||
|
return res.json();
|
||||||
|
},
|
||||||
|
|
||||||
|
async createEvent(event: CreateEventInput): Promise<Event> {
|
||||||
|
const res = await fetch(`${API_URL}/api/events`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(event),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error('Failed to create event');
|
||||||
|
return res.json();
|
||||||
|
},
|
||||||
|
|
||||||
|
async deleteEvent(id: string): Promise<void> {
|
||||||
|
const res = await fetch(`${API_URL}/api/events/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error('Failed to delete event');
|
||||||
|
},
|
||||||
|
};
|
||||||
34
admin/tsconfig.json
Normal file
34
admin/tsconfig.json
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2017",
|
||||||
|
"lib": ["dom", "dom.iterable", "esnext"],
|
||||||
|
"allowJs": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"module": "esnext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"incremental": true,
|
||||||
|
"plugins": [
|
||||||
|
{
|
||||||
|
"name": "next"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": [
|
||||||
|
"next-env.d.ts",
|
||||||
|
"**/*.ts",
|
||||||
|
"**/*.tsx",
|
||||||
|
".next/types/**/*.ts",
|
||||||
|
".next/dev/types/**/*.ts",
|
||||||
|
"**/*.mts"
|
||||||
|
],
|
||||||
|
"exclude": ["node_modules"]
|
||||||
|
}
|
||||||
98
backend/README.md
Normal file
98
backend/README.md
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
<p align="center">
|
||||||
|
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
|
||||||
|
[circleci-url]: https://circleci.com/gh/nestjs/nest
|
||||||
|
|
||||||
|
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
|
||||||
|
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
|
||||||
|
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
|
||||||
|
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
|
||||||
|
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
|
||||||
|
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
|
||||||
|
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
|
||||||
|
</p>
|
||||||
|
<!--[](https://opencollective.com/nest#backer)
|
||||||
|
[](https://opencollective.com/nest#sponsor)-->
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
|
||||||
|
|
||||||
|
## Project setup
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ pnpm install
|
||||||
|
```
|
||||||
|
|
||||||
|
## Compile and run the project
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# development
|
||||||
|
$ pnpm run start
|
||||||
|
|
||||||
|
# watch mode
|
||||||
|
$ pnpm run start:dev
|
||||||
|
|
||||||
|
# production mode
|
||||||
|
$ pnpm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# unit tests
|
||||||
|
$ pnpm run test
|
||||||
|
|
||||||
|
# e2e tests
|
||||||
|
$ pnpm run test:e2e
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
$ pnpm run test:cov
|
||||||
|
```
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
|
||||||
|
|
||||||
|
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
$ pnpm install -g @nestjs/mau
|
||||||
|
$ mau deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
Check out a few resources that may come in handy when working with NestJS:
|
||||||
|
|
||||||
|
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
|
||||||
|
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
|
||||||
|
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
|
||||||
|
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
|
||||||
|
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
|
||||||
|
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
|
||||||
|
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
|
||||||
|
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
|
||||||
|
|
||||||
|
## Stay in touch
|
||||||
|
|
||||||
|
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
|
||||||
|
- Website - [https://nestjs.com](https://nestjs.com/)
|
||||||
|
- Twitter - [@nestframework](https://twitter.com/nestframework)
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
|
||||||
107
backend/biome.json
Normal file
107
backend/biome.json
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json",
|
||||||
|
"vcs": {
|
||||||
|
"enabled": true,
|
||||||
|
"clientKind": "git",
|
||||||
|
"useIgnoreFile": true
|
||||||
|
},
|
||||||
|
"files": {
|
||||||
|
"ignoreUnknown": false,
|
||||||
|
"ignore": [
|
||||||
|
"node_modules",
|
||||||
|
"dist",
|
||||||
|
"coverage",
|
||||||
|
"migrations"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"formatter": {
|
||||||
|
"enabled": true,
|
||||||
|
"indentStyle": "space",
|
||||||
|
"indentWidth": 2,
|
||||||
|
"lineWidth": 100
|
||||||
|
},
|
||||||
|
"linter": {
|
||||||
|
"enabled": true,
|
||||||
|
"rules": {
|
||||||
|
"recommended": true,
|
||||||
|
"complexity": {
|
||||||
|
"noExtraBooleanCast": "error",
|
||||||
|
"noMultipleSpacesInRegularExpressionLiterals": "error",
|
||||||
|
"noUselessCatch": "error",
|
||||||
|
"noUselessTypeConstraint": "error",
|
||||||
|
"noWith": "error"
|
||||||
|
},
|
||||||
|
"correctness": {
|
||||||
|
"noConstAssign": "error",
|
||||||
|
"noConstantCondition": "error",
|
||||||
|
"noEmptyCharacterClassInRegex": "error",
|
||||||
|
"noEmptyPattern": "error",
|
||||||
|
"noGlobalObjectCalls": "error",
|
||||||
|
"noInvalidConstructorSuper": "error",
|
||||||
|
"noInvalidNewBuiltin": "error",
|
||||||
|
"noNonoctalDecimalEscape": "error",
|
||||||
|
"noPrecisionLoss": "error",
|
||||||
|
"noSelfAssign": "error",
|
||||||
|
"noSetterReturn": "error",
|
||||||
|
"noSwitchDeclarations": "error",
|
||||||
|
"noUndeclaredVariables": "error",
|
||||||
|
"noUnreachable": "error",
|
||||||
|
"noUnreachableSuper": "error",
|
||||||
|
"noUnsafeFinally": "error",
|
||||||
|
"noUnsafeOptionalChaining": "error",
|
||||||
|
"noUnusedLabels": "error",
|
||||||
|
"noUnusedVariables": "warn",
|
||||||
|
"useIsNan": "error",
|
||||||
|
"useValidForDirection": "error",
|
||||||
|
"useYield": "error"
|
||||||
|
},
|
||||||
|
"style": {
|
||||||
|
"noArguments": "error",
|
||||||
|
"noVar": "error",
|
||||||
|
"useConst": "error"
|
||||||
|
},
|
||||||
|
"suspicious": {
|
||||||
|
"noAsyncPromiseExecutor": "error",
|
||||||
|
"noCatchAssign": "error",
|
||||||
|
"noClassAssign": "error",
|
||||||
|
"noCompareNegZero": "error",
|
||||||
|
"noControlCharactersInRegex": "error",
|
||||||
|
"noDebugger": "error",
|
||||||
|
"noDoubleEquals": "warn",
|
||||||
|
"noDuplicateCase": "error",
|
||||||
|
"noDuplicateClassMembers": "error",
|
||||||
|
"noDuplicateObjectKeys": "error",
|
||||||
|
"noDuplicateParameters": "error",
|
||||||
|
"noEmptyBlockStatements": "error",
|
||||||
|
"noExplicitAny": "warn",
|
||||||
|
"noExtraNonNullAssertion": "error",
|
||||||
|
"noFallthroughSwitchClause": "error",
|
||||||
|
"noFunctionAssign": "error",
|
||||||
|
"noGlobalAssign": "error",
|
||||||
|
"noImportAssign": "error",
|
||||||
|
"noMisleadingCharacterClass": "error",
|
||||||
|
"noPrototypeBuiltins": "error",
|
||||||
|
"noRedeclare": "error",
|
||||||
|
"noShadowRestrictedNames": "error",
|
||||||
|
"noUnsafeNegation": "error",
|
||||||
|
"useGetterReturn": "error",
|
||||||
|
"useValidTypeof": "error"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"javascript": {
|
||||||
|
"formatter": {
|
||||||
|
"quoteStyle": "single",
|
||||||
|
"jsxQuoteStyle": "single",
|
||||||
|
"trailingCommas": "all",
|
||||||
|
"semicolons": "always",
|
||||||
|
"arrowParentheses": "always",
|
||||||
|
"bracketSpacing": true,
|
||||||
|
"bracketSameLine": false,
|
||||||
|
"quoteProperties": "asNeeded"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"organizeImports": {
|
||||||
|
"enabled": true
|
||||||
|
}
|
||||||
|
}
|
||||||
11
backend/drizzle.config.ts
Normal file
11
backend/drizzle.config.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { defineConfig } from 'drizzle-kit';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
schema: './src/database/schema.ts',
|
||||||
|
out: './migrations',
|
||||||
|
dialect: 'postgresql',
|
||||||
|
dbCredentials: {
|
||||||
|
// PGLite will be initialized in code
|
||||||
|
url: process.env.DATABASE_URL || 'postgresql://localhost/events',
|
||||||
|
},
|
||||||
|
});
|
||||||
17
backend/migrations/0000_lyrical_gabe_jones.sql
Normal file
17
backend/migrations/0000_lyrical_gabe_jones.sql
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
CREATE TABLE "events" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"title" text NOT NULL,
|
||||||
|
"emoji" text NOT NULL,
|
||||||
|
"month" integer NOT NULL,
|
||||||
|
"day" integer NOT NULL,
|
||||||
|
"start_year" integer,
|
||||||
|
"end_month" integer,
|
||||||
|
"end_day" integer,
|
||||||
|
"end_year" integer,
|
||||||
|
"description" text,
|
||||||
|
"color" text,
|
||||||
|
"is_active" boolean DEFAULT true NOT NULL,
|
||||||
|
"tags" text[],
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
126
backend/migrations/meta/0000_snapshot.json
Normal file
126
backend/migrations/meta/0000_snapshot.json
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
{
|
||||||
|
"id": "852b1a6a-31c7-4f44-bdef-a378a18e2c7d",
|
||||||
|
"prevId": "00000000-0000-0000-0000-000000000000",
|
||||||
|
"version": "7",
|
||||||
|
"dialect": "postgresql",
|
||||||
|
"tables": {
|
||||||
|
"public.events": {
|
||||||
|
"name": "events",
|
||||||
|
"schema": "",
|
||||||
|
"columns": {
|
||||||
|
"id": {
|
||||||
|
"name": "id",
|
||||||
|
"type": "uuid",
|
||||||
|
"primaryKey": true,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "gen_random_uuid()"
|
||||||
|
},
|
||||||
|
"title": {
|
||||||
|
"name": "title",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"emoji": {
|
||||||
|
"name": "emoji",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"month": {
|
||||||
|
"name": "month",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"day": {
|
||||||
|
"name": "day",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
"start_year": {
|
||||||
|
"name": "start_year",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"end_month": {
|
||||||
|
"name": "end_month",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"end_day": {
|
||||||
|
"name": "end_day",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"end_year": {
|
||||||
|
"name": "end_year",
|
||||||
|
"type": "integer",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"description": {
|
||||||
|
"name": "description",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"color": {
|
||||||
|
"name": "color",
|
||||||
|
"type": "text",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"is_active": {
|
||||||
|
"name": "is_active",
|
||||||
|
"type": "boolean",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": true
|
||||||
|
},
|
||||||
|
"tags": {
|
||||||
|
"name": "tags",
|
||||||
|
"type": "text[]",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": false
|
||||||
|
},
|
||||||
|
"created_at": {
|
||||||
|
"name": "created_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
},
|
||||||
|
"updated_at": {
|
||||||
|
"name": "updated_at",
|
||||||
|
"type": "timestamp with time zone",
|
||||||
|
"primaryKey": false,
|
||||||
|
"notNull": true,
|
||||||
|
"default": "now()"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"indexes": {},
|
||||||
|
"foreignKeys": {},
|
||||||
|
"compositePrimaryKeys": {},
|
||||||
|
"uniqueConstraints": {},
|
||||||
|
"policies": {},
|
||||||
|
"checkConstraints": {},
|
||||||
|
"isRLSEnabled": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"enums": {},
|
||||||
|
"schemas": {},
|
||||||
|
"sequences": {},
|
||||||
|
"roles": {},
|
||||||
|
"policies": {},
|
||||||
|
"views": {},
|
||||||
|
"_meta": {
|
||||||
|
"columns": {},
|
||||||
|
"schemas": {},
|
||||||
|
"tables": {}
|
||||||
|
}
|
||||||
|
}
|
||||||
13
backend/migrations/meta/_journal.json
Normal file
13
backend/migrations/meta/_journal.json
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"version": "7",
|
||||||
|
"dialect": "postgresql",
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"idx": 0,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1764421778123,
|
||||||
|
"tag": "0000_lyrical_gabe_jones",
|
||||||
|
"breakpoints": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
8
backend/nest-cli.json
Normal file
8
backend/nest-cli.json
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src",
|
||||||
|
"compilerOptions": {
|
||||||
|
"deleteOutDir": true
|
||||||
|
}
|
||||||
|
}
|
||||||
73
backend/package.json
Normal file
73
backend/package.json
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
{
|
||||||
|
"name": "@home-service/backend",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"description": "",
|
||||||
|
"author": "",
|
||||||
|
"private": true,
|
||||||
|
"license": "UNLICENSED",
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"format": "biome format --write ./src ./test",
|
||||||
|
"lint": "biome lint --write ./src ./test",
|
||||||
|
"check": "biome check --write ./src ./test",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"start:debug": "nest start --debug --watch",
|
||||||
|
"start:prod": "node dist/main",
|
||||||
|
"test": "jest",
|
||||||
|
"test:watch": "jest --watch",
|
||||||
|
"test:cov": "jest --coverage",
|
||||||
|
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@electric-sql/pglite": "^0.3.14",
|
||||||
|
"@nestjs/common": "^11.0.1",
|
||||||
|
"@nestjs/config": "^4.0.2",
|
||||||
|
"@nestjs/core": "^11.0.1",
|
||||||
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.3",
|
||||||
|
"date-fns": "^4.1.0",
|
||||||
|
"drizzle-orm": "^0.44.7",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.1",
|
||||||
|
"zod": "^4.1.13"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@biomejs/biome": "^1.9.4",
|
||||||
|
"@nestjs/cli": "^11.0.0",
|
||||||
|
"@nestjs/schematics": "^11.0.0",
|
||||||
|
"@nestjs/testing": "^11.0.1",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
|
"@types/node": "^22.19.1",
|
||||||
|
"@types/supertest": "^6.0.2",
|
||||||
|
"drizzle-kit": "^0.31.7",
|
||||||
|
"jest": "^30.0.0",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"ts-jest": "^29.2.5",
|
||||||
|
"ts-loader": "^9.5.2",
|
||||||
|
"ts-node": "^10.9.2",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.7.3"
|
||||||
|
},
|
||||||
|
"jest": {
|
||||||
|
"moduleFileExtensions": [
|
||||||
|
"js",
|
||||||
|
"json",
|
||||||
|
"ts"
|
||||||
|
],
|
||||||
|
"rootDir": "src",
|
||||||
|
"testRegex": ".*\\.spec\\.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
},
|
||||||
|
"collectCoverageFrom": [
|
||||||
|
"**/*.(t|j)s"
|
||||||
|
],
|
||||||
|
"coverageDirectory": "../coverage",
|
||||||
|
"testEnvironment": "node"
|
||||||
|
}
|
||||||
|
}
|
||||||
6433
backend/pnpm-lock.yaml
generated
Normal file
6433
backend/pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
15
backend/src/app.module.ts
Normal file
15
backend/src/app.module.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { DatabaseModule } from './database/database.module';
|
||||||
|
import { EventsModule } from './events/events.module';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
}),
|
||||||
|
DatabaseModule,
|
||||||
|
EventsModule,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
||||||
61
backend/src/database/database.module.ts
Normal file
61
backend/src/database/database.module.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import { Module, Global } from '@nestjs/common';
|
||||||
|
import { PGlite } from '@electric-sql/pglite';
|
||||||
|
import { drizzle, PgliteDatabase } from 'drizzle-orm/pglite';
|
||||||
|
import * as schema from './schema';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { existsSync, mkdirSync } from 'fs';
|
||||||
|
import { sql } from 'drizzle-orm';
|
||||||
|
|
||||||
|
export const DATABASE_CONNECTION = 'DATABASE_CONNECTION';
|
||||||
|
|
||||||
|
const databaseProvider = {
|
||||||
|
provide: DATABASE_CONNECTION,
|
||||||
|
useFactory: async (): Promise<PgliteDatabase<typeof schema>> => {
|
||||||
|
const dbPath = process.env.DATABASE_PATH || './data/events.db';
|
||||||
|
|
||||||
|
// Убедимся, что директория существует
|
||||||
|
const dbDir = dbPath.substring(0, dbPath.lastIndexOf('/'));
|
||||||
|
if (dbDir && !existsSync(dbDir)) {
|
||||||
|
mkdirSync(dbDir, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = new PGlite(dbPath);
|
||||||
|
const db = drizzle(client, { schema });
|
||||||
|
|
||||||
|
// Создаем таблицу напрямую вместо использования миграций
|
||||||
|
try {
|
||||||
|
await client.exec(`
|
||||||
|
CREATE TABLE IF NOT EXISTS events (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
emoji TEXT NOT NULL,
|
||||||
|
month INTEGER NOT NULL,
|
||||||
|
day INTEGER NOT NULL,
|
||||||
|
start_year INTEGER,
|
||||||
|
end_month INTEGER,
|
||||||
|
end_day INTEGER,
|
||||||
|
end_year INTEGER,
|
||||||
|
description TEXT,
|
||||||
|
color TEXT,
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT true,
|
||||||
|
tags TEXT[],
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
console.log('✅ Database initialized successfully');
|
||||||
|
} catch (error) {
|
||||||
|
console.error('❌ Error initializing database:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return db;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
providers: [databaseProvider],
|
||||||
|
exports: [DATABASE_CONNECTION],
|
||||||
|
})
|
||||||
|
export class DatabaseModule {}
|
||||||
39
backend/src/database/schema.ts
Normal file
39
backend/src/database/schema.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { pgTable, text, integer, boolean, timestamp, uuid } from 'drizzle-orm/pg-core';
|
||||||
|
import { sql } from 'drizzle-orm';
|
||||||
|
|
||||||
|
export const events = pgTable('events', {
|
||||||
|
id: uuid('id')
|
||||||
|
.primaryKey()
|
||||||
|
.default(sql`gen_random_uuid()`),
|
||||||
|
title: text('title').notNull(),
|
||||||
|
emoji: text('emoji').notNull(),
|
||||||
|
|
||||||
|
// Дата начала события (обязательно для всех типов)
|
||||||
|
month: integer('month').notNull(), // 1-12
|
||||||
|
day: integer('day').notNull(), // 1-31
|
||||||
|
|
||||||
|
// Год начала (опционально)
|
||||||
|
startYear: integer('start_year'),
|
||||||
|
|
||||||
|
// Дата окончания (опционально, для продолжительных событий)
|
||||||
|
endMonth: integer('end_month'), // 1-12
|
||||||
|
endDay: integer('end_day'), // 1-31
|
||||||
|
endYear: integer('end_year'),
|
||||||
|
|
||||||
|
// Дополнительные поля
|
||||||
|
description: text('description'),
|
||||||
|
color: text('color'), // hex формат
|
||||||
|
isActive: boolean('is_active').notNull().default(true),
|
||||||
|
tags: text('tags').array(),
|
||||||
|
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow()
|
||||||
|
.$onUpdate(() => new Date()),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type Event = typeof events.$inferSelect;
|
||||||
|
export type NewEvent = typeof events.$inferInsert;
|
||||||
60
backend/src/events/events.controller.ts
Normal file
60
backend/src/events/events.controller.ts
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import {
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Post,
|
||||||
|
Delete,
|
||||||
|
Body,
|
||||||
|
Param,
|
||||||
|
UsePipes,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { EventsService } from './events.service';
|
||||||
|
import type { CreateEventDto } from './schemas/event.schema';
|
||||||
|
import { createEventSchema } from './schemas/event.schema';
|
||||||
|
import { ZodValidationPipe } from '../pipes/zod-validation.pipe';
|
||||||
|
|
||||||
|
@Controller()
|
||||||
|
export class EventsController {
|
||||||
|
constructor(private readonly eventsService: EventsService) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Главный endpoint для виджета Glance
|
||||||
|
*/
|
||||||
|
@Get('countdown')
|
||||||
|
async getCountdown() {
|
||||||
|
return this.eventsService.getCountdownData();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получить все события
|
||||||
|
*/
|
||||||
|
@Get('api/events')
|
||||||
|
async findAll() {
|
||||||
|
return this.eventsService.findAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получить одно событие
|
||||||
|
*/
|
||||||
|
@Get('api/events/:id')
|
||||||
|
async findOne(@Param('id') id: string) {
|
||||||
|
return this.eventsService.findOne(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Создать событие
|
||||||
|
*/
|
||||||
|
@Post('api/events')
|
||||||
|
@UsePipes(new ZodValidationPipe(createEventSchema))
|
||||||
|
async create(@Body() createEventDto: CreateEventDto) {
|
||||||
|
return this.eventsService.create(createEventDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Удалить событие
|
||||||
|
*/
|
||||||
|
@Delete('api/events/:id')
|
||||||
|
async remove(@Param('id') id: string) {
|
||||||
|
await this.eventsService.remove(id);
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
10
backend/src/events/events.module.ts
Normal file
10
backend/src/events/events.module.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { EventsController } from './events.controller';
|
||||||
|
import { EventsService } from './events.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [EventsController],
|
||||||
|
providers: [EventsService],
|
||||||
|
exports: [EventsService],
|
||||||
|
})
|
||||||
|
export class EventsModule {}
|
||||||
200
backend/src/events/events.service.ts
Normal file
200
backend/src/events/events.service.ts
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
import { Injectable, Inject, NotFoundException } from '@nestjs/common';
|
||||||
|
import { PgliteDatabase } from 'drizzle-orm/pglite';
|
||||||
|
import { eq } from 'drizzle-orm';
|
||||||
|
import { DATABASE_CONNECTION } from '../database/database.module';
|
||||||
|
import { events, Event } from '../database/schema';
|
||||||
|
import { CreateEventDto } from './schemas/event.schema';
|
||||||
|
import {
|
||||||
|
getEventType,
|
||||||
|
getNextOccurrence,
|
||||||
|
calculateTimeDiff,
|
||||||
|
calculateAnniversary,
|
||||||
|
calculateDuration,
|
||||||
|
} from '../utils/datetime.utils';
|
||||||
|
import { addMonths, getDaysInMonth } from 'date-fns';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class EventsService {
|
||||||
|
constructor(
|
||||||
|
@Inject(DATABASE_CONNECTION)
|
||||||
|
private db: PgliteDatabase<typeof import('../database/schema')>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async findAll(): Promise<Event[]> {
|
||||||
|
return this.db.select().from(events).where(eq(events.isActive, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(id: string): Promise<Event> {
|
||||||
|
const [event] = await this.db
|
||||||
|
.select()
|
||||||
|
.from(events)
|
||||||
|
.where(eq(events.id, id));
|
||||||
|
|
||||||
|
if (!event) {
|
||||||
|
throw new NotFoundException(`Event with ID ${id} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(createEventDto: CreateEventDto): Promise<Event> {
|
||||||
|
const [event] = await this.db
|
||||||
|
.insert(events)
|
||||||
|
.values(createEventDto)
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
async update(id: string, updateEventDto: Partial<CreateEventDto>): Promise<Event> {
|
||||||
|
const [event] = await this.db
|
||||||
|
.update(events)
|
||||||
|
.set(updateEventDto)
|
||||||
|
.where(eq(events.id, id))
|
||||||
|
.returning();
|
||||||
|
|
||||||
|
if (!event) {
|
||||||
|
throw new NotFoundException(`Event with ID ${id} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return event;
|
||||||
|
}
|
||||||
|
|
||||||
|
async remove(id: string): Promise<void> {
|
||||||
|
await this.db.delete(events).where(eq(events.id, id));
|
||||||
|
// PGLite doesn't return rowCount, just assume it worked
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Получить все события с расчетами для виджета countdown
|
||||||
|
*/
|
||||||
|
async getCountdownData() {
|
||||||
|
const now = new Date();
|
||||||
|
const allEvents = await this.findAll();
|
||||||
|
|
||||||
|
const result = [];
|
||||||
|
|
||||||
|
for (const event of allEvents) {
|
||||||
|
const type = getEventType(event);
|
||||||
|
const processedEvent: any = {
|
||||||
|
id: event.id,
|
||||||
|
type,
|
||||||
|
emoji: event.emoji,
|
||||||
|
name: event.title,
|
||||||
|
description: event.description,
|
||||||
|
color: event.color,
|
||||||
|
tags: event.tags,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (type === 'recurring') {
|
||||||
|
// Обычное повторяющееся событие
|
||||||
|
const target = getNextOccurrence(now, event.month, event.day);
|
||||||
|
const { display, days, hours, minutes } = calculateTimeDiff(target, now);
|
||||||
|
|
||||||
|
processedEvent.date = target.toISOString().split('T')[0];
|
||||||
|
processedEvent.display = display;
|
||||||
|
processedEvent.days = days;
|
||||||
|
processedEvent.hours = hours;
|
||||||
|
processedEvent.minutes = minutes;
|
||||||
|
} else if (type === 'anniversary') {
|
||||||
|
// Годовщина
|
||||||
|
const { years, days } = calculateAnniversary(
|
||||||
|
event.startYear!,
|
||||||
|
event.month,
|
||||||
|
event.day,
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
const nextTarget = getNextOccurrence(now, event.month, event.day);
|
||||||
|
const { display, days: nextDays, hours, minutes } = calculateTimeDiff(nextTarget, now);
|
||||||
|
|
||||||
|
processedEvent.date = nextTarget.toISOString().split('T')[0];
|
||||||
|
processedEvent.startYear = event.startYear;
|
||||||
|
processedEvent.yearsPassed = years;
|
||||||
|
processedEvent.daysPassed = days;
|
||||||
|
processedEvent.display = display;
|
||||||
|
processedEvent.days = nextDays;
|
||||||
|
processedEvent.hours = hours;
|
||||||
|
processedEvent.minutes = minutes;
|
||||||
|
} else if (type === 'duration') {
|
||||||
|
// Продолжительное событие
|
||||||
|
const durationInfo = calculateDuration(
|
||||||
|
event.month,
|
||||||
|
event.day,
|
||||||
|
event.startYear!,
|
||||||
|
event.endMonth!,
|
||||||
|
event.endDay!,
|
||||||
|
event.endYear!,
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
|
||||||
|
processedEvent.startDate = new Date(event.startYear!, event.month - 1, event.day)
|
||||||
|
.toISOString()
|
||||||
|
.split('T')[0];
|
||||||
|
processedEvent.endDate = new Date(event.endYear!, event.endMonth! - 1, event.endDay!)
|
||||||
|
.toISOString()
|
||||||
|
.split('T')[0];
|
||||||
|
processedEvent.isActive = durationInfo.isActive;
|
||||||
|
processedEvent.daysUntilStart = durationInfo.daysUntilStart;
|
||||||
|
processedEvent.daysRemaining = durationInfo.daysRemaining;
|
||||||
|
processedEvent.totalDays = durationInfo.totalDays;
|
||||||
|
}
|
||||||
|
|
||||||
|
result.push(processedEvent);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Генерируем метки месяцев (как в Python версии)
|
||||||
|
const months = [];
|
||||||
|
let daysAccumulated = getDaysInMonth(now) - now.getDate();
|
||||||
|
|
||||||
|
for (let i = 0; i < 10; i++) {
|
||||||
|
const targetDate = addMonths(now, i);
|
||||||
|
const monthName = new Intl.DateTimeFormat('ru', { month: 'short' }).format(targetDate);
|
||||||
|
|
||||||
|
months.push({
|
||||||
|
name: monthName,
|
||||||
|
days: daysAccumulated,
|
||||||
|
});
|
||||||
|
|
||||||
|
daysAccumulated += getDaysInMonth(targetDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Timeline grid (как в Python версии)
|
||||||
|
const timelineGrid = [];
|
||||||
|
|
||||||
|
// Зона 1: 14 дней
|
||||||
|
for (let i = 0; i < 14; i++) {
|
||||||
|
const targetDate = new Date(now);
|
||||||
|
targetDate.setDate(now.getDate() + i);
|
||||||
|
|
||||||
|
timelineGrid.push({
|
||||||
|
days: i,
|
||||||
|
date: targetDate.toLocaleDateString('ru-RU'),
|
||||||
|
weekday: new Intl.DateTimeFormat('ru', { weekday: 'short' }).format(targetDate),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Зона 2: 40 недель
|
||||||
|
for (let i = 1; i <= 40; i++) {
|
||||||
|
const daysAhead = 14 + i * 7;
|
||||||
|
const targetDate = new Date(now);
|
||||||
|
targetDate.setDate(now.getDate() + daysAhead);
|
||||||
|
|
||||||
|
timelineGrid.push({
|
||||||
|
days: daysAhead,
|
||||||
|
date: targetDate.toLocaleDateString('ru-RU'),
|
||||||
|
weekday: new Intl.DateTimeFormat('ru', { weekday: 'short' }).format(targetDate),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
events: result,
|
||||||
|
current: {
|
||||||
|
year: now.getFullYear(),
|
||||||
|
month: now.getMonth() + 1,
|
||||||
|
day: now.getDate(),
|
||||||
|
},
|
||||||
|
months,
|
||||||
|
timelineGrid,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
50
backend/src/events/schemas/event.schema.ts
Normal file
50
backend/src/events/schemas/event.schema.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Базовая схема события
|
||||||
|
export const createEventSchema = z.object({
|
||||||
|
title: z.string().min(1, 'Название обязательно'),
|
||||||
|
emoji: z.string().min(1, 'Эмодзи обязательно'),
|
||||||
|
month: z.number().int().min(1).max(12),
|
||||||
|
day: z.number().int().min(1).max(31),
|
||||||
|
startYear: z.number().int().min(1900).max(2100).optional().nullable(),
|
||||||
|
endMonth: z.number().int().min(1).max(12).optional().nullable(),
|
||||||
|
endDay: z.number().int().min(1).max(31).optional().nullable(),
|
||||||
|
endYear: z.number().int().min(1900).max(2100).optional().nullable(),
|
||||||
|
description: z.string().optional().nullable(),
|
||||||
|
color: z.string().regex(/^#[0-9A-Fa-f]{6}$/).optional().nullable(),
|
||||||
|
isActive: z.boolean().optional().default(true),
|
||||||
|
tags: z.array(z.string()).optional().nullable(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateEventSchema = createEventSchema.partial();
|
||||||
|
|
||||||
|
export const eventResponseSchema = z.object({
|
||||||
|
id: z.string().uuid(),
|
||||||
|
type: z.enum(['recurring', 'anniversary', 'duration']),
|
||||||
|
title: z.string(),
|
||||||
|
emoji: z.string(),
|
||||||
|
month: z.number(),
|
||||||
|
day: z.number(),
|
||||||
|
startYear: z.number().nullable(),
|
||||||
|
endMonth: z.number().nullable(),
|
||||||
|
endDay: z.number().nullable(),
|
||||||
|
endYear: z.number().nullable(),
|
||||||
|
description: z.string().nullable(),
|
||||||
|
color: z.string().nullable(),
|
||||||
|
isActive: z.boolean(),
|
||||||
|
tags: z.array(z.string()).nullable(),
|
||||||
|
createdAt: z.date(),
|
||||||
|
updatedAt: z.date(),
|
||||||
|
// Вычисленные поля
|
||||||
|
date: z.string().optional(),
|
||||||
|
display: z.string().optional(),
|
||||||
|
days: z.number().optional(),
|
||||||
|
hours: z.number().optional(),
|
||||||
|
minutes: z.number().optional(),
|
||||||
|
yearsПassed: z.number().optional(),
|
||||||
|
daysPassed: z.number().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export type CreateEventDto = z.infer<typeof createEventSchema>;
|
||||||
|
export type UpdateEventDto = z.infer<typeof updateEventSchema>;
|
||||||
|
export type EventResponseDto = z.infer<typeof eventResponseSchema>;
|
||||||
20
backend/src/main.ts
Normal file
20
backend/src/main.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
const app = await NestFactory.create(AppModule);
|
||||||
|
|
||||||
|
// Enable CORS
|
||||||
|
app.enableCors({
|
||||||
|
origin: process.env.CORS_ORIGIN || 'http://localhost:3001',
|
||||||
|
credentials: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const port = process.env.PORT || 3000;
|
||||||
|
await app.listen(port);
|
||||||
|
|
||||||
|
console.log(`🚀 Application is running on: http://localhost:${port}`);
|
||||||
|
console.log(`📊 Countdown endpoint: http://localhost:${port}/countdown`);
|
||||||
|
}
|
||||||
|
|
||||||
|
bootstrap();
|
||||||
18
backend/src/pipes/zod-validation.pipe.ts
Normal file
18
backend/src/pipes/zod-validation.pipe.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
|
||||||
|
import type { ZodSchema } from 'zod';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ZodValidationPipe implements PipeTransform {
|
||||||
|
constructor(private schema: ZodSchema) {}
|
||||||
|
|
||||||
|
transform(value: unknown) {
|
||||||
|
try {
|
||||||
|
const parsedValue = this.schema.parse(value);
|
||||||
|
return parsedValue;
|
||||||
|
} catch (error) {
|
||||||
|
throw new BadRequestException('Validation failed', {
|
||||||
|
cause: error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
197
backend/src/utils/datetime.utils.ts
Normal file
197
backend/src/utils/datetime.utils.ts
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
import {
|
||||||
|
addYears,
|
||||||
|
differenceInDays,
|
||||||
|
differenceInHours,
|
||||||
|
differenceInMinutes,
|
||||||
|
differenceInSeconds,
|
||||||
|
isAfter,
|
||||||
|
isBefore,
|
||||||
|
setMonth,
|
||||||
|
setDate,
|
||||||
|
startOfDay,
|
||||||
|
} from 'date-fns';
|
||||||
|
|
||||||
|
export type EventType = 'recurring' | 'anniversary' | 'duration';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Определяет тип события по заполненным полям
|
||||||
|
*/
|
||||||
|
export function getEventType(event: {
|
||||||
|
startYear?: number | null;
|
||||||
|
endYear?: number | null;
|
||||||
|
endMonth?: number | null;
|
||||||
|
endDay?: number | null;
|
||||||
|
}): EventType {
|
||||||
|
const hasEndDate =
|
||||||
|
event.endYear != null &&
|
||||||
|
event.endMonth != null &&
|
||||||
|
event.endDay != null;
|
||||||
|
|
||||||
|
if (hasEndDate) {
|
||||||
|
return 'duration';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event.startYear != null) {
|
||||||
|
return 'anniversary';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'recurring';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Рассчитывает следующее наступление ежегодного события
|
||||||
|
*/
|
||||||
|
export function getNextOccurrence(
|
||||||
|
now: Date,
|
||||||
|
month: number,
|
||||||
|
day: number,
|
||||||
|
): Date {
|
||||||
|
const currentYear = now.getFullYear();
|
||||||
|
let target = new Date(currentYear, month - 1, day); // month is 1-indexed
|
||||||
|
|
||||||
|
// Если дата уже прошла в этом году, используем следующий год
|
||||||
|
if (isBefore(target, now)) {
|
||||||
|
target = addYears(target, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return startOfDay(target);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Расч итывает разницу во времени между двумя датами
|
||||||
|
*/
|
||||||
|
export function calculateTimeDiff(target: Date, now: Date): {
|
||||||
|
display: string;
|
||||||
|
days: number;
|
||||||
|
hours: number;
|
||||||
|
minutes: number;
|
||||||
|
} {
|
||||||
|
const diff = differenceInSeconds(target, now);
|
||||||
|
|
||||||
|
if (diff > 0) {
|
||||||
|
const days = Math.floor(diff / 86400);
|
||||||
|
const hours = Math.floor((diff % 86400) / 3600);
|
||||||
|
const minutes = Math.floor((diff % 3600) / 60);
|
||||||
|
|
||||||
|
return {
|
||||||
|
display: formatTimeRemaining(days, hours, minutes),
|
||||||
|
days,
|
||||||
|
hours,
|
||||||
|
minutes,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
display: '✅ Свершилось!',
|
||||||
|
days: 0,
|
||||||
|
hours: 0,
|
||||||
|
minutes: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Форматирует оставшееся время в читаемую строку
|
||||||
|
*/
|
||||||
|
export function formatTimeRemaining(
|
||||||
|
days: number,
|
||||||
|
hours: number,
|
||||||
|
minutes: number,
|
||||||
|
): string {
|
||||||
|
return `${days}д ${hours}ч ${minutes}м`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Рассчитывает годовщину
|
||||||
|
*/
|
||||||
|
export function calculateAnniversary(
|
||||||
|
startYear: number,
|
||||||
|
month: number,
|
||||||
|
day: number,
|
||||||
|
now: Date,
|
||||||
|
): {
|
||||||
|
years: number;
|
||||||
|
days: number;
|
||||||
|
} {
|
||||||
|
// Получаем следующую дату годовщины
|
||||||
|
const nextOccurrence = getNextOccurrence(now, month, day);
|
||||||
|
const years = nextOccurrence.getFullYear() - startYear;
|
||||||
|
|
||||||
|
// Дополнительные дни от прошлой годовщины
|
||||||
|
const startDate = new Date(startYear, month - 1, day);
|
||||||
|
const diffInDays = differenceInDays(now, startDate);
|
||||||
|
const fullYears = Math.floor(diffInDays / 365.25);
|
||||||
|
const remainingDays = diffInDays - Math.floor(fullYears * 365.25);
|
||||||
|
|
||||||
|
return {
|
||||||
|
years,
|
||||||
|
days: remainingDays,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Рассчитывает информацию о продолжительном событии
|
||||||
|
*/
|
||||||
|
export function calculateDuration(
|
||||||
|
startMonth: number,
|
||||||
|
startDay: number,
|
||||||
|
startYear: number,
|
||||||
|
endMonth: number,
|
||||||
|
endDay: number,
|
||||||
|
endYear: number,
|
||||||
|
now: Date,
|
||||||
|
): {
|
||||||
|
isActive: boolean;
|
||||||
|
daysUntilStart?: number;
|
||||||
|
daysUntilEnd?: number;
|
||||||
|
daysRemaining?: number;
|
||||||
|
totalDays: number;
|
||||||
|
} {
|
||||||
|
const startDate = new Date(startYear, startMonth - 1, startDay);
|
||||||
|
const endDate = new Date(endYear, endMonth - 1, endDay);
|
||||||
|
const totalDays = differenceInDays(endDate, startDate);
|
||||||
|
|
||||||
|
const isActive = isAfter(now, startDate) && isBefore(now, endDate);
|
||||||
|
|
||||||
|
if (isBefore(now, startDate)) {
|
||||||
|
// Событие еще не началось
|
||||||
|
return {
|
||||||
|
isActive: false,
|
||||||
|
daysUntilStart: differenceInDays(startDate, now),
|
||||||
|
totalDays,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isAfter(now, endDate)) {
|
||||||
|
// Событие уже закончилось
|
||||||
|
return {
|
||||||
|
isActive: false,
|
||||||
|
totalDays,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Событие активно
|
||||||
|
return {
|
||||||
|
isActive: true,
|
||||||
|
daysRemaining: differenceInDays(endDate, now),
|
||||||
|
daysUntilEnd: differenceInDays(endDate, now),
|
||||||
|
totalDays,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Проверяет, идет ли событие прямо сейчас
|
||||||
|
*/
|
||||||
|
export function isEventActive(
|
||||||
|
startMonth: number,
|
||||||
|
startDay: number,
|
||||||
|
startYear: number,
|
||||||
|
endMonth: number,
|
||||||
|
endDay: number,
|
||||||
|
endYear: number,
|
||||||
|
now: Date,
|
||||||
|
): boolean {
|
||||||
|
const startDate = new Date(startYear, startMonth - 1, startDay);
|
||||||
|
const endDate = new Date(endYear, endMonth - 1, endDay);
|
||||||
|
|
||||||
|
return isAfter(now, startDate) && isBefore(now, endDate);
|
||||||
|
}
|
||||||
25
backend/test/app.e2e-spec.ts
Normal file
25
backend/test/app.e2e-spec.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { App } from 'supertest/types';
|
||||||
|
import { AppModule } from './../src/app.module';
|
||||||
|
|
||||||
|
describe('AppController (e2e)', () => {
|
||||||
|
let app: INestApplication<App>;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleFixture.createNestApplication();
|
||||||
|
await app.init();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/ (GET)', () => {
|
||||||
|
return request(app.getHttpServer())
|
||||||
|
.get('/')
|
||||||
|
.expect(200)
|
||||||
|
.expect('Hello World!');
|
||||||
|
});
|
||||||
|
});
|
||||||
9
backend/test/jest-e2e.json
Normal file
9
backend/test/jest-e2e.json
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"moduleFileExtensions": ["js", "json", "ts"],
|
||||||
|
"rootDir": ".",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
}
|
||||||
|
}
|
||||||
4
backend/tsconfig.build.json
Normal file
4
backend/tsconfig.build.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
|
}
|
||||||
25
backend/tsconfig.json
Normal file
25
backend/tsconfig.json
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "nodenext",
|
||||||
|
"moduleResolution": "nodenext",
|
||||||
|
"resolvePackageJsonExports": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"declaration": true,
|
||||||
|
"removeComments": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "ES2023",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strictNullChecks": true,
|
||||||
|
"forceConsistentCasingInFileNames": true,
|
||||||
|
"noImplicitAny": true,
|
||||||
|
"strictBindCallApply": true,
|
||||||
|
"noFallthroughCasesInSwitch": true
|
||||||
|
}
|
||||||
|
}
|
||||||
22
package.json
Normal file
22
package.json
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "home-service",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Home Service Monorepo",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "turbo dev",
|
||||||
|
"build": "turbo build",
|
||||||
|
"lint": "turbo lint",
|
||||||
|
"format": "turbo format",
|
||||||
|
"test": "turbo test",
|
||||||
|
"clean": "turbo clean && rm -rf node_modules"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"turbo": "^2.3.3"
|
||||||
|
},
|
||||||
|
"packageManager": "pnpm@9.15.0",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0",
|
||||||
|
"pnpm": ">=9.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
9349
pnpm-lock.yaml
generated
Normal file
9349
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
3
pnpm-workspace.yaml
Normal file
3
pnpm-workspace.yaml
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
packages:
|
||||||
|
- 'admin'
|
||||||
|
- 'backend'
|
||||||
47
turbo.json
Normal file
47
turbo.json
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://turbo.build/schema.json",
|
||||||
|
"ui": "stream",
|
||||||
|
"tasks": {
|
||||||
|
"build": {
|
||||||
|
"dependsOn": [
|
||||||
|
"^build"
|
||||||
|
],
|
||||||
|
"outputs": [
|
||||||
|
".next/**",
|
||||||
|
"!.next/cache/**",
|
||||||
|
"dist/**"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"dev": {
|
||||||
|
"cache": false,
|
||||||
|
"persistent": true
|
||||||
|
},
|
||||||
|
"lint": {
|
||||||
|
"dependsOn": [
|
||||||
|
"^lint"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"format": {
|
||||||
|
"cache": false
|
||||||
|
},
|
||||||
|
"check": {
|
||||||
|
"dependsOn": [
|
||||||
|
"^check"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"test": {
|
||||||
|
"dependsOn": [
|
||||||
|
"^build"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"test:watch": {
|
||||||
|
"cache": false,
|
||||||
|
"persistent": true
|
||||||
|
},
|
||||||
|
"test:e2e": {
|
||||||
|
"dependsOn": [
|
||||||
|
"^build"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user