Compare commits

..

6 Commits

87 changed files with 3626 additions and 15691 deletions

35
.dockerignore Normal file
View File

@@ -0,0 +1,35 @@
# Dependencies
node_modules
**/node_modules
# Build output
.next
dist
.turbo
# Development
*.log
.env
.env.local
.env.*.local
# IDE
.vscode
.idea
*.swp
# Data
backend/data
# Git
.git
.gitignore
# Docker
Dockerfile*
docker-compose*
.dockerignore
# Misc
README.md
*.md

223
README.md
View File

@@ -1,26 +1,30 @@
# home-service # home-service
Современный монорепозиторий для сервиса домашней автоматизации с бэкендом и админ-панелью. Современный монорепозиторий для домашнего сервиса с бэкендом и фронтенд-панелью.
## 🚀 Стек технологий ## 🚀 Стек технологий
**Инфраструктура:** **Инфраструктура:**
- Turborepo - система сборки монорепозитория - Turborepo - система сборки монорепозитория
- pnpm Workspaces - управление зависимостями - pnpm Workspaces - управление зависимостями
- Docker - контейнеризация
**Backend:** **Backend:**
- NestJS 10 - NestJS 11
- PGLite (встроенная PostgreSQL БД) - PGLite (встроенная PostgreSQL БД)
- Drizzle ORM - Drizzle ORM
- Zod для валидации - Zod для валидации
- date-fns для работы с датами - Swagger для API документации
**Admin:** **Frontend:**
- Next.js 16 (App Router) - Next.js 16 (App Router)
- React 19 - React 19
- TailwindCSS 4 - TailwindCSS 4
- TypeScript - TypeScript
**Contracts:**
- Shared Zod схемы между backend и frontend
## 📁 Структура проекта ## 📁 Структура проекта
``` ```
@@ -28,39 +32,29 @@ home-service/
├── backend/ # NestJS API (@home-service/backend) ├── backend/ # NestJS API (@home-service/backend)
│ ├── src/ │ ├── src/
│ │ ├── database/ # Схема БД и модуль │ │ ├── database/ # Схема БД и модуль
│ │ ├── events/ # Модуль событий │ │ ├── wishlist/ # Модуль списка желаний
│ │ ── utils/ # Утилиты для дат │ │ ── common/ # Общие утилиты
│ │ └── pipes/ # Zod validation pipe
│ ├── migrations/ # Миграции БД │ ├── migrations/ # Миграции БД
── data/ # База данных PGLite ── data/ # База данных PGLite
│ └── Dockerfile # Docker образ
├── admin/ # Next.js админка (@home-service/admin) ├── frontend/ # Next.js панель (@home-service/frontend)
── src/ ── src/
├── app/ # Страницы ├── app/ # Страницы (wishlist, admin)
├── components/ # React компоненты ├── components/ # React компоненты
└── lib/ # API клиент └── lib/ # API клиент
│ ├── templates/ # HTML мокапы
│ └── Dockerfile # Docker образ
├── turbo.json # Конфигурация Turborepo ├── contracts/ # Shared типы (@home-service/contracts)
│ └── src/ # Zod схемы
├── docker-compose.yml # Docker Compose
├── turbo.json # Конфигурация Turborepo
├── pnpm-workspace.yaml # Конфигурация pnpm workspaces ├── pnpm-workspace.yaml # Конфигурация pnpm workspaces
└── package.json # Корневой package.json └── package.json # Корневой package.json
``` ```
## 🎯 Типы событий
База данных поддерживает три типа событий. Тип определяется автоматически по заполненным полям:
1. **recurring** - Обычное повторяющееся событие
- Поля: `month`, `day`
- Пример: Новый год, 8 марта
2. **anniversary** - Годовщина с отслеживанием времени
- Поля: `month`, `day`, `startYear`
- Пример: день рождения, свадьба
3. **duration** - Продолжительное событие
- Поля: `month`, `day`, `startYear`, `endMonth`, `endDay`, `endYear`
- Пример: отпуск, командировка
## ⚡ Быстрый старт ## ⚡ Быстрый старт
### Требования ### Требования
@@ -86,13 +80,14 @@ pnpm dev
# Запустить только backend # Запустить только backend
pnpm --filter @home-service/backend dev pnpm --filter @home-service/backend dev
# Запустить только admin # Запустить только frontend
pnpm --filter @home-service/admin dev pnpm --filter @home-service/frontend dev
``` ```
**Адреса:** **Адреса:**
- Backend API: `http://localhost:3000` - Backend API: `http://localhost:3000`
- Admin панель: `http://localhost:3001` - Frontend панель: `http://localhost:3001`
- Swagger: `http://localhost:3000/api-docs`
### Сборка ### Сборка
@@ -103,8 +98,8 @@ pnpm build
# Собрать только backend # Собрать только backend
pnpm --filter @home-service/backend build pnpm --filter @home-service/backend build
# Собрать только admin # Собрать только frontend
pnpm --filter @home-service/admin build pnpm --filter @home-service/frontend build
``` ```
### Другие команды ### Другие команды
@@ -116,63 +111,75 @@ pnpm lint
# Форматирование (для backend с Biome) # Форматирование (для backend с Biome)
pnpm format pnpm format
# Тестирование
pnpm test
# Очистка всех node_modules и кеша # Очистка всех node_modules и кеша
pnpm clean pnpm clean
``` ```
## 🐳 Docker
### Быстрый запуск
```bash
# Собрать и запустить все сервисы
docker-compose up -d
# Посмотреть логи
docker-compose logs -f
# Остановить
docker-compose down
```
### Сборка образов отдельно
```bash
# Backend
docker build -f backend/Dockerfile -t home-service-backend .
# Frontend
docker build -f frontend/Dockerfile -t home-service-frontend .
```
**Docker адреса:**
- Backend API: `http://localhost:3000`
- Frontend панель: `http://localhost:3001`
### Volumes
- `backend-data` - хранит данные PGLite базы данных
## API Endpoints ## API Endpoints
### GET /countdown ### Wishlist API
Главный endpoint для виджета Glance. Возвращает все события с расчетами.
**Ответ:** | Метод | Endpoint | Описание |
```json |-------|----------|----------|
{ | GET | `/wishlist` | Получить все элементы |
"events": [ | GET | `/wishlist/:id` | Получить элемент по ID |
{ | POST | `/wishlist` | Создать новый элемент |
"id": "uuid", | PUT | `/wishlist/:id` | Обновить элемент |
"type": "recurring", | DELETE | `/wishlist/:id` | Удалить элемент |
"emoji": "🎄",
"name": "Новый год", ### Создание элемента
"date": "2026-01-01",
"display": "365д 5ч 36м", ```bash
"days": 365, curl -X POST http://localhost:3000/wishlist \
"hours": 5, -H "Content-Type: application/json" \
"minutes": 36 -d '{
} "title": "PlayStation 5",
], "price": 49999,
"current": { "description": "Игровая консоль",
"year": 2025, "links": [{"title": "Купить", "url": "https://store.example.com", "isPrimary": true}],
"month": 11, "images": [{"url": "https://example.com/ps5.jpg", "isMain": true}]
"day": 29 }'
},
"months": [...],
"timelineGrid": [...]
}
``` ```
### GET /api/events ### Swagger
Получить все события
### POST /api/events Полная документация API доступна по адресу:
Создать новое событие ```
http://localhost:3000/api-docs
**Body:**
```json
{
"title": "День рождения",
"emoji": "🎂",
"month": 6,
"day": 15,
"startYear": 1990
}
``` ```
### DELETE /api/events/:id
Удалить событие
## Конфигурация ## Конфигурация
@@ -180,51 +187,19 @@ pnpm clean
``` ```
PORT=3000 PORT=3000
CORS_ORIGIN=http://localhost:3001 CORS_ORIGIN=http://localhost:3001
DATABASE_PATH=./data/events.db DATABASE_PATH=./data/home-service.db
``` ```
### Admin (.env.local) ### Frontend (.env.local)
``` ```
NEXT_PUBLIC_API_URL=http://localhost:3000 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 ```bash
pnpm --filter @home-service/backend exec drizzle-kit generate pnpm --filter @home-service/backend db:generate
``` ```
### Применение миграций ### Применение миграций
@@ -242,6 +217,20 @@ rm -rf .turbo
pnpm clean pnpm clean
``` ```
## 🚢 Production
### Все приложения
```bash
pnpm build
pnpm --filter @home-service/backend start:prod
pnpm --filter @home-service/frontend start
```
### С Docker (рекомендуется)
```bash
docker-compose up -d
```
## Лицензия ## Лицензия
MIT MIT

41
admin/.gitignore vendored
View File

@@ -1,41 +0,0 @@
# 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

View File

@@ -1,36 +0,0 @@
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.

View File

@@ -1,18 +0,0 @@
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;

View File

@@ -1,7 +0,0 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

View File

@@ -1,26 +0,0 @@
{
"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

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +0,0 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

View File

@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 391 B

View File

@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 128 B

View File

@@ -1 +0,0 @@
<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>

Before

Width:  |  Height:  |  Size: 385 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -1,26 +0,0 @@
@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;
}

View File

@@ -1,27 +0,0 @@
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>
);
}

View File

@@ -1,87 +0,0 @@
'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>
);
}

View File

@@ -1,266 +0,0 @@
'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>
);
}

View File

@@ -1,74 +0,0 @@
'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>
);
}

View File

@@ -1,491 +0,0 @@
'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>
);
}

View File

@@ -1,56 +0,0 @@
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');
},
};

3
backend/.env.example Normal file
View File

@@ -0,0 +1,3 @@
PORT=3000
CORS_ORIGIN=http://localhost:3001
DATABASE_PATH=./data/home-service.db

5
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
node_modules
dist
.env
data
migrations

67
backend/Dockerfile Normal file
View File

@@ -0,0 +1,67 @@
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
# Enable pnpm
RUN corepack enable pnpm
# Copy workspace configuration files
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
COPY contracts/package.json ./contracts/
COPY backend/package.json ./backend/
# Install all dependencies (including dev for build)
RUN pnpm install --frozen-lockfile
# Copy source code
COPY contracts ./contracts
COPY backend ./backend
# Build contracts first (workspace dependency)
RUN pnpm --filter @home-service/contracts build
# Build backend
RUN pnpm --filter @home-service/backend build
# Stage 2: Production
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
# Enable pnpm for production install
RUN corepack enable pnpm
# Copy workspace configuration for pnpm install
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
COPY contracts/package.json ./contracts/
COPY backend/package.json ./backend/
# Install production dependencies only
RUN pnpm install --frozen-lockfile --prod
# Copy built artifacts
COPY --from=builder /app/backend/dist ./backend/dist
COPY --from=builder /app/contracts/dist ./contracts/dist
# Copy migrations folder
COPY --from=builder /app/backend/migrations ./backend/migrations
# Copy drizzle config for migrations
COPY --from=builder /app/backend/drizzle.config.ts ./backend/
# Create data directory for PGLite
RUN mkdir -p /data
# Create startup script that runs migrations then starts app
RUN echo '#!/bin/sh' > /app/start.sh && \
echo 'cd /app/backend' >> /app/start.sh && \
echo 'node -e "const{drizzle}=require(\"drizzle-orm/pglite\");const{PGlite}=require(\"@electric-sql/pglite\");const{migrate}=require(\"drizzle-orm/pglite/migrator\");(async()=>{const c=new PGlite(process.env.DATABASE_PATH||\"./data/home-service.db\");const d=drizzle(c);await migrate(d,{migrationsFolder:\"./migrations\"});console.log(\"Migrations done\")})().catch(e=>{console.error(e);process.exit(1)})"' >> /app/start.sh && \
echo 'exec node dist/main.js' >> /app/start.sh && \
chmod +x /app/start.sh
WORKDIR /app/backend
EXPOSE 3000
CMD ["/app/start.sh"]

View File

@@ -1,98 +0,0 @@
<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>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](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).

View File

@@ -1,107 +1,18 @@
{ {
"$schema": "https://biomejs.dev/schemas/1.9.4/schema.json", "$schema": "https://biomejs.dev/schemas/1.9.0/schema.json",
"vcs": { "organizeImports": {
"enabled": true, "enabled": true
"clientKind": "git",
"useIgnoreFile": true
}, },
"files": { "linter": {
"ignoreUnknown": false, "enabled": true,
"ignore": [ "rules": {
"node_modules", "recommended": true
"dist", }
"coverage",
"migrations"
]
}, },
"formatter": { "formatter": {
"enabled": true, "enabled": true,
"indentStyle": "space", "indentStyle": "space",
"indentWidth": 2, "indentWidth": 2,
"lineWidth": 100 "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
} }
} }

View File

@@ -1,11 +1,10 @@
import { defineConfig } from 'drizzle-kit'; import { defineConfig } from 'drizzle-kit';
export default defineConfig({ export default defineConfig({
schema: './src/database/schema.ts', schema: './src/database/schema.ts',
out: './migrations', out: './migrations',
dialect: 'postgresql', dialect: 'postgresql',
dbCredentials: { dbCredentials: {
// PGLite will be initialized in code url: process.env.DATABASE_PATH || './data/home-service.db',
url: process.env.DATABASE_URL || 'postgresql://localhost/events', },
},
}); });

View File

@@ -1,17 +0,0 @@
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
);

View File

@@ -1,126 +0,0 @@
{
"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": {}
}
}

View File

@@ -1,13 +0,0 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1764421778123,
"tag": "0000_lyrical_gabe_jones",
"breakpoints": true
}
]
}

View File

@@ -1,8 +1,8 @@
{ {
"$schema": "https://json.schemastore.org/nest-cli", "$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics", "collection": "@nestjs/schematics",
"sourceRoot": "src", "sourceRoot": "src",
"compilerOptions": { "compilerOptions": {
"deleteOutDir": true "deleteOutDir": true
} }
} }

View File

@@ -1,73 +1,41 @@
{ {
"name": "@home-service/backend", "name": "@home-service/backend",
"version": "0.0.1", "version": "1.0.0",
"description": "", "description": "Home Service Backend API",
"author": "", "private": true,
"private": true, "scripts": {
"license": "UNLICENSED", "dev": "nest start --watch --preserveWatchOutput",
"scripts": { "build": "nest build",
"build": "nest build", "start": "node dist/main",
"format": "biome format --write ./src ./test", "start:prod": "node dist/main",
"lint": "biome lint --write ./src ./test", "lint": "biome check .",
"check": "biome check --write ./src ./test", "format": "biome format --write .",
"start": "nest start", "db:generate": "drizzle-kit generate",
"start:dev": "nest start --watch", "db:migrate": "tsx src/database/migrate.ts"
"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": [ "dependencies": {
"**/*.(t|j)s" "@electric-sql/pglite": "^0.2.0",
], "@home-service/contracts": "workspace:*",
"coverageDirectory": "../coverage", "@nestjs/common": "^11.0.0",
"testEnvironment": "node" "@nestjs/core": "^11.0.0",
} "@nestjs/platform-express": "^11.0.0",
"@nestjs/swagger": "^8.0.0",
"drizzle-orm": "^0.36.0",
"nestjs-zod": "^5.0.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"zod": "^3.23.0"
},
"devDependencies": {
"@biomejs/biome": "^1.9.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@types/node": "^22.0.0",
"drizzle-kit": "^0.28.0",
"tsx": "^4.19.0",
"typescript": "^5.6.0"
},
"engines": {
"node": ">=20.0.0"
}
} }

6433
backend/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +1,8 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { DatabaseModule } from './database/database.module'; import { DatabaseModule } from './database/database.module';
import { EventsModule } from './events/events.module'; import { WishlistModule } from './wishlist/wishlist.module';
@Module({ @Module({
imports: [ imports: [DatabaseModule, WishlistModule],
ConfigModule.forRoot({
isGlobal: true,
}),
DatabaseModule,
EventsModule,
],
}) })
export class AppModule {} export class AppModule { }

View File

@@ -0,0 +1,18 @@
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
import { ZodSchema } from 'zod';
@Injectable()
export class ZodValidationPipe implements PipeTransform {
constructor(private schema: ZodSchema) { }
transform(value: unknown) {
try {
return this.schema.parse(value);
} catch (error) {
throw new BadRequestException({
message: 'Validation failed',
errors: error.errors,
});
}
}
}

View File

@@ -1,61 +1,14 @@
import { Module, Global } from '@nestjs/common'; import { Global, Module } from '@nestjs/common';
import { PGlite } from '@electric-sql/pglite'; import { db } from './db';
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() @Global()
@Module({ @Module({
providers: [databaseProvider], providers: [
exports: [DATABASE_CONNECTION], {
provide: 'DATABASE',
useValue: db,
},
],
exports: ['DATABASE'],
}) })
export class DatabaseModule {} export class DatabaseModule { }

View File

@@ -0,0 +1,6 @@
import { drizzle } from 'drizzle-orm/pglite';
import { PGlite } from '@electric-sql/pglite';
import * as schema from './schema';
const client = new PGlite(process.env.DATABASE_PATH || './data/home-service.db');
export const db = drizzle(client, { schema });

View File

@@ -0,0 +1,14 @@
import { db } from './db';
import { migrate } from 'drizzle-orm/pglite/migrator';
async function runMigrations() {
console.log('Running migrations...');
await migrate(db, { migrationsFolder: './migrations' });
console.log('Migrations completed!');
process.exit(0);
}
runMigrations().catch((err) => {
console.error('Migration failed:', err);
process.exit(1);
});

View File

@@ -1,39 +1,48 @@
import { pgTable, text, integer, boolean, timestamp, uuid } from 'drizzle-orm/pg-core'; import { pgTable, uuid, varchar, text, decimal, integer, boolean, timestamp } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm'; import { relations } from 'drizzle-orm';
export const events = pgTable('events', { export const wishlistItems = pgTable('wishlist_items', {
id: uuid('id') id: uuid('id').primaryKey().defaultRandom(),
.primaryKey() title: varchar('title', { length: 255 }).notNull(),
.default(sql`gen_random_uuid()`), price: decimal('price', { precision: 10, scale: 2 }),
title: text('title').notNull(), description: text('description'),
emoji: text('emoji').notNull(), note: text('note'),
createdAt: timestamp('created_at').notNull().defaultNow(),
// Дата начала события (обязательно для всех типов) updatedAt: timestamp('updated_at').notNull().defaultNow(),
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 const wishlistImages = pgTable('wishlist_images', {
export type NewEvent = typeof events.$inferInsert; id: uuid('id').primaryKey().defaultRandom(),
itemId: uuid('item_id').notNull().references(() => wishlistItems.id, { onDelete: 'cascade' }),
url: varchar('url', { length: 500 }).notNull(),
isMain: boolean('is_main').notNull().default(false),
sortOrder: integer('sort_order').notNull().default(0),
});
export const wishlistLinks = pgTable('wishlist_links', {
id: uuid('id').primaryKey().defaultRandom(),
itemId: uuid('item_id').notNull().references(() => wishlistItems.id, { onDelete: 'cascade' }),
title: varchar('title', { length: 100 }).notNull(),
url: varchar('url', { length: 500 }).notNull(),
isPrimary: boolean('is_primary').notNull().default(false),
});
// Relations
export const wishlistItemsRelations = relations(wishlistItems, ({ many }) => ({
images: many(wishlistImages),
links: many(wishlistLinks),
}));
export const wishlistImagesRelations = relations(wishlistImages, ({ one }) => ({
item: one(wishlistItems, {
fields: [wishlistImages.itemId],
references: [wishlistItems.id],
}),
}));
export const wishlistLinksRelations = relations(wishlistLinks, ({ one }) => ({
item: one(wishlistItems, {
fields: [wishlistLinks.itemId],
references: [wishlistItems.id],
}),
}));

View File

@@ -1,60 +0,0 @@
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 };
}
}

View File

@@ -1,10 +0,0 @@
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 {}

View File

@@ -1,200 +0,0 @@
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,
};
}
}

View File

@@ -1,50 +0,0 @@
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>;

View File

@@ -1,20 +1,31 @@
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ZodValidationPipe } from 'nestjs-zod';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ZodValidationPipe());
// Enable CORS // CORS
app.enableCors({ app.enableCors({
origin: process.env.CORS_ORIGIN || 'http://localhost:3001', origin: process.env.CORS_ORIGIN || 'http://localhost:3001',
credentials: true, credentials: true,
}); });
const port = process.env.PORT || 3000; // Swagger
await app.listen(port); const config = new DocumentBuilder()
.setTitle('Home Service API')
.setDescription('API для домашнего сервиса')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
console.log(`🚀 Application is running on: http://localhost:${port}`); const port = process.env.PORT || 3000;
console.log(`📊 Countdown endpoint: http://localhost:${port}/countdown`); await app.listen(port);
console.log(`🚀 Server running on http://localhost:${port}`);
console.log(`📚 Swagger docs: http://localhost:${port}/api`);
} }
bootstrap(); bootstrap();

View File

@@ -1,18 +0,0 @@
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,
});
}
}
}

View File

@@ -1,197 +0,0 @@
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);
}

View File

@@ -0,0 +1,4 @@
import { createZodDto } from 'nestjs-zod';
import { CreateWishlistItemSchema } from '@home-service/contracts';
export class CreateWishlistItemDto extends createZodDto(CreateWishlistItemSchema) { }

View File

@@ -0,0 +1,4 @@
import { createZodDto } from 'nestjs-zod';
import { UpdateWishlistItemSchema } from '@home-service/contracts';
export class UpdateWishlistItemDto extends createZodDto(UpdateWishlistItemSchema) { }

View File

@@ -0,0 +1,60 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
HttpCode,
HttpStatus,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { WishlistService } from './wishlist.service';
import { CreateWishlistItemDto } from './dto/create-wishlist-item.dto';
import { UpdateWishlistItemDto } from './dto/update-wishlist-item.dto';
@ApiTags('wishlist')
@Controller('wishlist')
export class WishlistController {
constructor(private readonly wishlistService: WishlistService) { }
@Get()
@ApiOperation({ summary: 'Get all wishlist items' })
@ApiResponse({ status: 200, description: 'Returns all wishlist items' })
findAll() {
return this.wishlistService.findAll();
}
@Get(':id')
@ApiOperation({ summary: 'Get wishlist item by ID' })
@ApiResponse({ status: 200, description: 'Returns the wishlist item' })
@ApiResponse({ status: 404, description: 'Item not found' })
findOne(@Param('id') id: string) {
return this.wishlistService.findOne(id);
}
@Post()
@ApiOperation({ summary: 'Create new wishlist item' })
@ApiResponse({ status: 201, description: 'Item created successfully' })
create(@Body() createDto: CreateWishlistItemDto) {
return this.wishlistService.create(createDto);
}
@Put(':id')
@ApiOperation({ summary: 'Update wishlist item' })
@ApiResponse({ status: 200, description: 'Item updated successfully' })
@ApiResponse({ status: 404, description: 'Item not found' })
update(@Param('id') id: string, @Body() updateDto: UpdateWishlistItemDto) {
return this.wishlistService.update(id, updateDto);
}
@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT)
@ApiOperation({ summary: 'Delete wishlist item' })
@ApiResponse({ status: 204, description: 'Item deleted successfully' })
@ApiResponse({ status: 404, description: 'Item not found' })
remove(@Param('id') id: string) {
return this.wishlistService.remove(id);
}
}

View File

@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { WishlistController } from './wishlist.controller';
import { WishlistService } from './wishlist.service';
@Module({
controllers: [WishlistController],
providers: [WishlistService],
})
export class WishlistModule { }

View File

@@ -0,0 +1,147 @@
import { Injectable, Inject, NotFoundException } from '@nestjs/common';
import { eq } from 'drizzle-orm';
import type { NodePgDatabase } from 'drizzle-orm/node-postgres';
import * as schema from '../database/schema';
import type { CreateWishlistItem, UpdateWishlistItem } from '@home-service/contracts';
@Injectable()
export class WishlistService {
constructor(@Inject('DATABASE') private db: NodePgDatabase<typeof schema>) { }
async findAll() {
const items = await this.db.query.wishlistItems.findMany({
with: {
images: {
orderBy: (images, { asc }) => [asc(images.sortOrder)],
},
links: true,
},
orderBy: (items, { asc }) => [asc(items.createdAt)],
});
return items.map(this.mapToDTO);
}
async findOne(id: string) {
const item = await this.db.query.wishlistItems.findFirst({
where: eq(schema.wishlistItems.id, id),
with: {
images: {
orderBy: (images, { asc }) => [asc(images.sortOrder)],
},
links: true,
},
});
if (!item) {
throw new NotFoundException(`Wishlist item with ID ${id} not found`);
}
return this.mapToDTO(item);
}
async create(data: CreateWishlistItem) {
const [item] = await this.db
.insert(schema.wishlistItems)
.values({
title: data.title,
price: data.price?.toString(),
description: data.description,
note: data.note,
})
.returning();
// Insert images
if (data.images && data.images.length > 0) {
await this.db.insert(schema.wishlistImages).values(
data.images.map((img, idx) => ({
itemId: item.id,
url: img.url,
isMain: img.isMain,
sortOrder: img.sortOrder ?? idx,
})),
);
}
// Insert links
if (data.links && data.links.length > 0) {
await this.db.insert(schema.wishlistLinks).values(
data.links.map((link) => ({
itemId: item.id,
title: link.title,
url: link.url,
isPrimary: link.isPrimary,
})),
);
}
return this.findOne(item.id);
}
async update(id: string, data: UpdateWishlistItem) {
await this.findOne(id); // Check if exists
await this.db
.update(schema.wishlistItems)
.set({
title: data.title,
price: data.price?.toString(),
description: data.description,
note: data.note,
updatedAt: new Date(),
})
.where(eq(schema.wishlistItems.id, id));
// Update images if provided
if (data.images) {
await this.db.delete(schema.wishlistImages).where(eq(schema.wishlistImages.itemId, id));
if (data.images.length > 0) {
await this.db.insert(schema.wishlistImages).values(
data.images.map((img, idx) => ({
itemId: id,
url: img.url,
isMain: img.isMain,
sortOrder: img.sortOrder ?? idx,
})),
);
}
}
// Update links if provided
if (data.links) {
await this.db.delete(schema.wishlistLinks).where(eq(schema.wishlistLinks.itemId, id));
if (data.links.length > 0) {
await this.db.insert(schema.wishlistLinks).values(
data.links.map((link) => ({
itemId: id,
title: link.title,
url: link.url,
isPrimary: link.isPrimary,
})),
);
}
}
return this.findOne(id);
}
async remove(id: string) {
await this.findOne(id); // Check if exists
await this.db.delete(schema.wishlistItems).where(eq(schema.wishlistItems.id, id));
return { message: 'Item deleted successfully' };
}
private mapToDTO(item: any) {
return {
id: item.id,
title: item.title,
price: item.price ? Number.parseFloat(item.price) : undefined,
description: item.description,
note: item.note,
images: item.images || [],
links: item.links || [],
createdAt: item.createdAt.toISOString(),
updatedAt: item.updatedAt.toISOString(),
};
}
}

View File

@@ -1,25 +0,0 @@
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!');
});
});

View File

@@ -1,9 +0,0 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}

View File

@@ -1,4 +0,0 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}

View File

@@ -1,25 +1,30 @@
{ {
"compilerOptions": { "compilerOptions": {
"module": "nodenext", "module": "commonjs",
"moduleResolution": "nodenext", "declaration": true,
"resolvePackageJsonExports": true, "removeComments": true,
"esModuleInterop": true, "emitDecoratorMetadata": true,
"isolatedModules": true, "experimentalDecorators": true,
"declaration": true, "allowSyntheticDefaultImports": true,
"removeComments": true, "target": "ES2021",
"emitDecoratorMetadata": true, "sourceMap": true,
"experimentalDecorators": true, "outDir": "./dist",
"allowSyntheticDefaultImports": true, "baseUrl": "./",
"target": "ES2023", "incremental": true,
"sourceMap": true, "skipLibCheck": true,
"outDir": "./dist", "strictNullChecks": true,
"baseUrl": "./", "noImplicitAny": true,
"incremental": true, "strictBindCallApply": false,
"skipLibCheck": true, "forceConsistentCasingInFileNames": false,
"strictNullChecks": true, "noFallthroughCasesInSwitch": false,
"forceConsistentCasingInFileNames": true, "esModuleInterop": true,
"noImplicitAny": true, "resolveJsonModule": true
"strictBindCallApply": true, },
"noFallthroughCasesInSwitch": true "include": [
} "src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
} }

2
contracts/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules
dist

18
contracts/package.json Normal file
View File

@@ -0,0 +1,18 @@
{
"name": "@home-service/contracts",
"version": "1.0.0",
"description": "Shared contracts and types",
"private": true,
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsc",
"dev": "tsc --watch"
},
"dependencies": {
"zod": "^3.23.0"
},
"devDependencies": {
"typescript": "^5.6.0"
}
}

1
contracts/src/index.ts Normal file
View File

@@ -0,0 +1 @@
export * from './wishlist';

53
contracts/src/wishlist.ts Normal file
View File

@@ -0,0 +1,53 @@
import { z } from 'zod';
// Wishlist Link Schema
export const WishlistLinkSchema = z.object({
id: z.string().uuid().optional(),
title: z.string().min(1, 'Название ссылки обязательно'),
url: z.string().url('Некорректный URL'),
isPrimary: z.boolean().default(false),
});
export type WishlistLink = z.infer<typeof WishlistLinkSchema>;
// Wishlist Image Schema
export const WishlistImageSchema = z.object({
id: z.string().uuid().optional(),
url: z.string().url('Некорректный URL изображения'),
isMain: z.boolean().default(false),
sortOrder: z.number().int().default(0),
});
export type WishlistImage = z.infer<typeof WishlistImageSchema>;
// Wishlist Item Schema
export const WishlistItemSchema = z.object({
id: z.string().uuid(),
title: z.string().min(1, 'Название обязательно'),
price: z.number().positive('Цена должна быть положительной').optional(),
description: z.string().optional(),
note: z.string().optional(),
images: z.array(WishlistImageSchema).default([]),
links: z.array(WishlistLinkSchema).default([]),
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
});
export type WishlistItem = z.infer<typeof WishlistItemSchema>;
// Create Wishlist Item DTO
export const CreateWishlistItemSchema = WishlistItemSchema.omit({
id: true,
createdAt: true,
updatedAt: true,
}).extend({
images: z.array(WishlistImageSchema.omit({ id: true })).default([]),
links: z.array(WishlistLinkSchema.omit({ id: true })).default([]),
});
export type CreateWishlistItem = z.infer<typeof CreateWishlistItemSchema>;
// Update Wishlist Item DTO
export const UpdateWishlistItemSchema = CreateWishlistItemSchema.partial();
export type UpdateWishlistItem = z.infer<typeof UpdateWishlistItemSchema>;

20
contracts/tsconfig.json Normal file
View File

@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2021",
"module": "commonjs",
"declaration": true,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
}

33
docker-compose.yml Normal file
View File

@@ -0,0 +1,33 @@
services:
backend:
build:
context: .
dockerfile: backend/Dockerfile
ports:
- "3000:3000"
environment:
- PORT=3000
- CORS_ORIGIN=http://localhost:3001
- DATABASE_PATH=/data/home-service.db
volumes:
- backend-data:/data
restart: unless-stopped
frontend:
build:
context: .
dockerfile: frontend/Dockerfile
args:
# Client-side API URL (public, goes to browser)
NEXT_PUBLIC_API_URL: http://localhost:3000
ports:
- "3001:3001"
environment:
# Server-side API URL (for SSR, inside Docker network)
- API_URL=http://backend:3000
depends_on:
- backend
restart: unless-stopped
volumes:
backend-data:

1
frontend/.env.example Normal file
View File

@@ -0,0 +1 @@
NEXT_PUBLIC_API_URL=http://localhost:3000

5
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
node_modules
.next
out
.env.local
.env

51
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,51 @@
# Stage 1: Build
FROM node:20-alpine AS builder
WORKDIR /app
# Enable pnpm
RUN corepack enable pnpm
# Build args for Next.js public env vars (inlined at build time)
ARG NEXT_PUBLIC_API_URL=http://localhost:3000
# Copy workspace configuration files
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json ./
COPY contracts/package.json ./contracts/
COPY frontend/package.json ./frontend/
# Install dependencies
RUN pnpm install --frozen-lockfile
# Copy source code
COPY contracts ./contracts
COPY frontend ./frontend
# Build contracts first (workspace dependency)
RUN pnpm --filter @home-service/contracts build
# Set env for build and build frontend
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
RUN pnpm --filter @home-service/frontend build
# Stage 2: Production
FROM node:20-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3001
ENV HOSTNAME="0.0.0.0"
# For server-side API calls (inside Docker network)
ENV API_URL=http://backend:3000
# Copy standalone build output (monorepo structure puts it in frontend subfolder)
COPY --from=builder /app/frontend/.next/standalone ./
COPY --from=builder /app/frontend/.next/static ./frontend/.next/static
# Copy public folder if exists
COPY --from=builder /app/frontend/public ./frontend/public
EXPOSE 3001
WORKDIR /app/frontend
CMD ["node", "server.js"]

6
frontend/next-env.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

14
frontend/next.config.mjs Normal file
View File

@@ -0,0 +1,14 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'images.unsplash.com',
},
],
},
};
export default nextConfig;

28
frontend/package.json Normal file
View File

@@ -0,0 +1,28 @@
{
"name": "@home-service/frontend",
"version": "1.0.0",
"description": "Home Service Frontend",
"private": true,
"scripts": {
"dev": "next dev -p 3001",
"build": "next build",
"start": "next start -p 3001",
"lint": "next lint"
},
"dependencies": {
"@home-service/contracts": "workspace:*",
"next": "^16.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"zod": "^3.23.0"
},
"devDependencies": {
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"eslint": "^9.0.0",
"eslint-config-next": "^16.0.0",
"tailwindcss": "^4.0.0",
"typescript": "^5.6.0"
}
}

1
frontend/public/.gitkeep Normal file
View File

@@ -0,0 +1 @@
.gitkeep

View File

@@ -0,0 +1,76 @@
import WishlistForm from '@/components/WishlistForm';
import Link from 'next/link';
const styles = {
container: {
minHeight: '100vh',
fontFamily: "'JetBrains Mono', 'Courier New', monospace",
fontSize: '13px',
background: '#0c0c0c',
color: '#c0c0c0',
padding: '40px',
},
wrapper: {
maxWidth: '800px',
margin: '0 auto',
},
header: {
background: '#111',
border: '1px solid #222',
padding: '20px 24px',
marginBottom: '24px',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
},
headerTitle: {
fontSize: '20px',
fontWeight: 600,
color: '#22c55e',
},
headerSubtitle: {
fontSize: '11px',
color: '#666',
marginTop: '4px',
},
backLink: {
fontSize: '11px',
color: '#666',
textDecoration: 'none',
padding: '6px 12px',
border: '1px solid #222',
},
};
export default function AdminWishlistPage() {
return (
<div style={styles.container}>
<div style={styles.wrapper}>
{/* HEADER */}
<header style={styles.header}>
<div>
<h1 style={styles.headerTitle}>
<span style={{ color: '#666' }}>&gt; </span>
ADMIN_PANEL
<span style={{ animation: 'blink 1s step-end infinite' }}>_</span>
</h1>
<p style={styles.headerSubtitle}>// Create new wishlist item</p>
</div>
<Link href="/wishlist" style={styles.backLink}>
[ BACK TO LIST ]
</Link>
</header>
{/* FORM */}
<WishlistForm />
</div>
<style>{`
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
`}</style>
</div>
);
}

View File

@@ -0,0 +1,34 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Reset */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: #0c0c0c;
}
::-webkit-scrollbar-thumb {
background: #222;
}
::-webkit-scrollbar-thumb:hover {
background: #444;
}
/* Selection */
::selection {
background: #22c55e;
color: #000;
}

View File

@@ -0,0 +1,36 @@
import type { Metadata } from 'next';
import './globals.css';
export const metadata: Metadata = {
title: 'SYSTEM_WISHLIST_V2.0',
description: 'Home Service Terminal Interface',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="ru">
<head>
<link
href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&display=swap"
rel="stylesheet"
/>
</head>
<body style={{
margin: 0,
padding: 0,
background: '#0c0c0c',
color: '#c0c0c0',
fontFamily: "'JetBrains Mono', 'Courier New', monospace",
fontSize: '13px',
lineHeight: 1.6,
minHeight: '100vh',
}}>
{children}
</body>
</html>
);
}

View File

@@ -0,0 +1,5 @@
import { redirect } from 'next/navigation';
export default function HomePage() {
redirect('/wishlist');
}

View File

@@ -0,0 +1,163 @@
import { wishlistApi } from '@/lib/api';
import WishlistItem from '@/components/WishlistItem';
import Link from 'next/link';
const styles = {
container: {
minHeight: '100vh',
fontFamily: "'JetBrains Mono', 'Courier New', monospace",
fontSize: '13px',
background: '#0c0c0c',
color: '#c0c0c0',
},
sidebar: {
width: '200px',
background: '#0c0c0c',
borderRight: '1px solid #222',
padding: '16px',
position: 'fixed' as const,
left: 0,
top: 0,
height: '100vh',
overflowY: 'auto' as const,
zIndex: 50,
},
sidebarHeader: {
marginBottom: '24px',
paddingBottom: '16px',
borderBottom: '1px dashed #222',
},
sidebarTitle: {
fontSize: '14px',
fontWeight: 600,
color: '#22c55e',
},
sidebarVersion: {
fontSize: '11px',
color: '#666',
marginTop: '4px',
},
navSection: {
marginBottom: '24px',
},
navTitle: {
fontSize: '11px',
color: '#22d3ee',
marginBottom: '8px',
},
navItem: {
display: 'block',
padding: '4px 0',
paddingLeft: '16px',
color: '#666',
textDecoration: 'none',
fontSize: '12px',
},
adminLink: {
display: 'block',
textAlign: 'center' as const,
padding: '4px 10px',
background: '#22c55e',
border: '1px solid #22c55e',
color: '#000',
textDecoration: 'none',
fontSize: '11px',
},
main: {
marginLeft: '220px',
maxWidth: '800px',
padding: '40px 32px',
},
pageHeader: {
marginBottom: '32px',
paddingBottom: '16px',
borderBottom: '1px solid #222',
},
pageTitle: {
fontSize: '16px',
fontWeight: 600,
color: '#facc15',
},
pageSubtitle: {
color: '#666',
fontSize: '12px',
marginTop: '8px',
},
emptyCard: {
background: '#111',
border: '1px solid #222',
padding: '32px',
textAlign: 'center' as const,
},
};
export default async function WishlistPage() {
const items = await wishlistApi.getAll();
return (
<div style={styles.container}>
{/* SIDEBAR */}
<aside style={styles.sidebar}>
<div style={styles.sidebarHeader}>
<h1 style={styles.sidebarTitle}>
<span style={{ color: '#666' }}>$ </span>wishlist
</h1>
<p style={styles.sidebarVersion}>
<span style={{ color: '#666' }}># </span>v1.0.0
</p>
</div>
<nav style={styles.navSection}>
<div style={styles.navTitle}>
<span style={{ color: '#666' }}> </span>items<span style={{ color: '#666' }}> </span>
</div>
{items.map((item, idx) => (
<a
key={item.id}
href={`#item-${item.id}`}
style={styles.navItem}
>
<span style={{ color: '#666' }}>{idx === items.length - 1 ? '└─ ' : '├─ '}</span>
{item.title}
</a>
))}
</nav>
<div style={{ paddingTop: '16px', borderTop: '1px dashed #222' }}>
<Link href="/admin/wishlist" style={styles.adminLink}>
[admin]
</Link>
</div>
</aside>
{/* MAIN CONTENT */}
<main style={styles.main}>
<header style={styles.pageHeader}>
<h2 style={styles.pageTitle}>
<span style={{ color: '#666' }}> </span>wishlist --list
</h2>
<p style={styles.pageSubtitle}>
<span style={{ color: '#666' }}> </span>
Найдено {items.length} элементов в списке желаний
</p>
</header>
<div>
{items.length === 0 ? (
<div style={styles.emptyCard}>
<div style={{ fontSize: '48px', marginBottom: '16px' }}>📦</div>
<p style={{ color: '#666', marginBottom: '16px' }}>Список пуст</p>
<Link href="/admin/wishlist" style={styles.adminLink}>
[добавить элемент]
</Link>
</div>
) : (
items.map((item, index) => (
<WishlistItem key={item.id} item={item} index={index} />
))
)}
</div>
</main>
</div>
);
}

View File

@@ -0,0 +1,53 @@
import type { WishlistItem } from '@home-service/contracts';
interface Props {
items: WishlistItem[];
}
export default function Sidebar({ items }: Props) {
const totalValue = items.reduce((sum, item) => sum + (item.price || 0), 0);
return (
<aside className="col-span-1 lg:col-span-3 order-1 lg:order-2">
<div className="sticky top-8">
<div className="term-border p-4 mb-6 bg-term-bg/90 backdrop-blur-sm">
<h3 className="text-xl font-bold mb-4 border-b border-term-dim pb-2">&gt; ITEM_LIST</h3>
<nav className="flex flex-col gap-1 text-sm">
{items.map((item, idx) => (
<a
key={item.id}
href={`#item-${item.id}`}
className="nav-link px-2 py-1 flex justify-between group transition-all"
>
<span>
{String(idx + 1).padStart(2, '0')}_{item.title.replace(/\s+/g, '_')}
</span>
<span className="text-term-dim group-hover:text-black opacity-0 group-hover:opacity-100">
&lt;
</span>
</a>
))}
</nav>
</div>
<div className="term-border p-4 text-xs text-term-dim bg-term-bg">
<h4 className="font-bold text-term-green mb-2">&gt; DEBUG_INFO</h4>
<ul className="space-y-1 font-mono">
<li className="flex justify-between">
<span>ITEMS:</span> <span>{items.length}</span>
</li>
<li className="flex justify-between">
<span>TOTAL_VAL:</span> <span>~{(totalValue / 1000).toFixed(1)}K</span>
</li>
<li className="flex justify-between">
<span>UPDATED:</span> <span>{new Date().toLocaleDateString('ru-RU')}</span>
</li>
</ul>
<div className="mt-4 pt-2 border-t border-term-dim text-center opacity-50">
[ SYSTEM READY ]
</div>
</div>
</div>
</aside>
);
}

View File

@@ -0,0 +1,112 @@
'use client';
import { useEffect } from 'react';
import type { WishlistItem } from '@home-service/contracts';
interface Props {
items: WishlistItem[];
}
export default function SidebarNav({ items }: Props) {
useEffect(() => {
// Smooth Scroll
const handleClick = (e: Event) => {
const target = e.currentTarget as HTMLAnchorElement;
const targetId = target.getAttribute('href');
if (!targetId) return;
e.preventDefault();
const targetEl = document.querySelector(targetId);
if (targetEl) {
targetEl.scrollIntoView({
behavior: 'smooth'
});
// Update URL hash without jumping
history.pushState(null, '', targetId);
}
};
const links = document.querySelectorAll('a[href^="#"]');
links.forEach(anchor => {
anchor.addEventListener('click', handleClick);
});
// Intersection Observer for Item highlighting in Menu
const observerOptions = {
root: null,
rootMargin: '-20% 0px -60% 0px', // Active zone in the middle of screen
threshold: 0
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const id = entry.target.getAttribute('id');
document.querySelectorAll('.nav-link').forEach(link => {
link.classList.remove('active-link');
if (link.getAttribute('href') === `#${id}`) {
link.classList.add('active-link');
}
});
}
});
}, observerOptions);
document.querySelectorAll('article').forEach((section) => {
observer.observe(section);
});
return () => {
links.forEach(anchor => {
anchor.removeEventListener('click', handleClick);
});
observer.disconnect();
};
}, []);
const totalValue = items.reduce((sum, item) => sum + (item.price || 0), 0);
return (
<aside className="col-span-1 lg:col-span-4">
<div className="sticky top-8">
<div className="term-border p-4 mb-6 bg-term-bg/90 backdrop-blur-sm">
<h3 className="text-xl font-bold mb-4 border-b border-term-dim pb-2">&gt; ITEM_LIST</h3>
<nav className="flex flex-col gap-1 text-sm">
{items.map((item, idx) => (
<a
key={item.id}
href={`#item-${item.id}`}
className="nav-link px-2 py-1 flex justify-between group transition-all"
>
<span>
{String(idx + 1).padStart(2, '0')}_{item.title.replace(/\s+/g, '_')}
</span>
<span className="text-term-dim group-hover:text-black opacity-0 group-hover:opacity-100">
&lt;
</span>
</a>
))}
</nav>
</div>
<div className="term-border p-4 text-xs text-term-dim bg-term-bg">
<h4 className="font-bold text-term-green mb-2">&gt; DEBUG_INFO</h4>
<ul className="space-y-1 font-mono">
<li className="flex justify-between">
<span>ITEMS:</span> <span>{items.length}</span>
</li>
<li className="flex justify-between">
<span>TOTAL_VAL:</span> <span>~{(totalValue / 1000).toFixed(1)}K</span>
</li>
<li className="flex justify-between">
<span>UPDATED:</span> <span>{new Date().toLocaleDateString('ru-RU')}</span>
</li>
</ul>
<div className="mt-4 pt-2 border-t border-term-dim text-center opacity-50">
[ SYSTEM READY ]
</div>
</div>
</div>
</aside>
);
}

View File

@@ -0,0 +1,427 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { wishlistApi } from '@/lib/api';
import type { CreateWishlistItem } from '@home-service/contracts';
const styles = {
section: {
background: '#111',
border: '1px solid #222',
marginBottom: '20px',
},
sectionHeader: {
background: '#1a1a1a',
padding: '12px 16px',
borderBottom: '1px solid #222',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
},
sectionTitle: {
color: '#22c55e',
fontWeight: 500,
},
sectionBody: {
padding: '20px',
},
formGroup: {
marginBottom: '16px',
},
label: {
display: 'block',
color: '#22d3ee',
fontSize: '11px',
marginBottom: '6px',
},
input: {
width: '100%',
background: '#0a0a0a',
border: '1px solid #222',
padding: '10px 12px',
color: '#22c55e',
fontFamily: 'inherit',
fontSize: '13px',
outline: 'none',
},
textarea: {
width: '100%',
background: '#0a0a0a',
border: '1px solid #222',
padding: '10px 12px',
color: '#22c55e',
fontFamily: 'inherit',
fontSize: '13px',
outline: 'none',
resize: 'vertical' as const,
minHeight: '80px',
},
dynamicItem: {
display: 'flex',
gap: '8px',
alignItems: 'center',
marginBottom: '12px',
padding: '12px',
background: '#0a0a0a',
border: '1px dashed #222',
},
inputFlex: {
flex: 1,
background: '#0a0a0a',
border: '1px solid #222',
padding: '10px 12px',
color: '#22c55e',
fontFamily: 'inherit',
fontSize: '13px',
outline: 'none',
},
inputSmall: {
width: '120px',
background: '#0a0a0a',
border: '1px solid #222',
padding: '10px 12px',
color: '#22c55e',
fontFamily: 'inherit',
fontSize: '13px',
outline: 'none',
},
checkboxLabel: {
display: 'flex',
alignItems: 'center',
gap: '6px',
color: '#666',
fontSize: '11px',
whiteSpace: 'nowrap' as const,
cursor: 'pointer',
},
btnRemove: {
background: 'none',
border: 'none',
color: '#f87171',
cursor: 'pointer',
padding: '4px 8px',
fontSize: '14px',
},
btnAdd: {
fontSize: '11px',
color: '#666',
textDecoration: 'none',
padding: '4px 10px',
border: '1px solid #222',
background: 'none',
cursor: 'pointer',
},
formActions: {
display: 'flex',
gap: '12px',
marginTop: '24px',
},
btn: {
flex: 1,
padding: '12px 20px',
fontFamily: 'inherit',
fontSize: '12px',
border: '1px solid #222',
background: 'none',
color: '#666',
cursor: 'pointer',
textAlign: 'center' as const,
},
btnPrimary: {
flex: 1,
padding: '12px 20px',
fontFamily: 'inherit',
fontSize: '12px',
background: '#22c55e',
border: '1px solid #22c55e',
color: '#000',
cursor: 'pointer',
textAlign: 'center' as const,
},
error: {
background: 'rgba(248, 113, 113, 0.1)',
border: '1px solid #f87171',
color: '#f87171',
padding: '12px 16px',
marginBottom: '20px',
},
};
export default function WishlistForm() {
const router = useRouter();
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [formData, setFormData] = useState<Partial<CreateWishlistItem>>({
title: '',
price: undefined,
description: '',
note: '',
images: [],
links: [],
});
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
setError('');
try {
await wishlistApi.create(formData as CreateWishlistItem);
router.push('/wishlist');
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to create item');
} finally {
setLoading(false);
}
};
const addImage = () => {
setFormData((prev) => ({
...prev,
images: [...(prev.images || []), { url: '', isMain: false, sortOrder: prev.images?.length || 0 }],
}));
};
const updateImage = (index: number, field: 'url' | 'isMain', value: string | boolean) => {
setFormData((prev) => ({
...prev,
images: prev.images?.map((img, i) =>
i === index ? { ...img, [field]: value } : field === 'isMain' && value ? { ...img, isMain: false } : img
),
}));
};
const removeImage = (index: number) => {
setFormData((prev) => ({
...prev,
images: prev.images?.filter((_, i) => i !== index),
}));
};
const addLink = () => {
setFormData((prev) => ({
...prev,
links: [...(prev.links || []), { title: '', url: '', isPrimary: false }],
}));
};
const updateLink = (index: number, field: 'title' | 'url' | 'isPrimary', value: string | boolean) => {
setFormData((prev) => ({
...prev,
links: prev.links?.map((link, i) =>
i === index ? { ...link, [field]: value } : field === 'isPrimary' && value ? { ...link, isPrimary: false } : link
),
}));
};
const removeLink = (index: number) => {
setFormData((prev) => ({
...prev,
links: prev.links?.filter((_, i) => i !== index),
}));
};
return (
<form onSubmit={handleSubmit}>
{error && (
<div style={styles.error}>
ERROR: {error}
</div>
)}
{/* Basic Info */}
<section style={styles.section}>
<div style={styles.sectionHeader}>
<span style={styles.sectionTitle}>
<span style={{ color: '#f87171' }}> </span>
basic_info
<span style={{ color: '#facc15' }}> </span>
</span>
</div>
<div style={styles.sectionBody}>
<div style={styles.formGroup}>
<label style={styles.label}>
<span style={{ color: '#666' }}>// </span>
Title <span style={{ color: '#f87171' }}>*</span>
</label>
<input
type="text"
required
value={formData.title}
onChange={(e) => setFormData({ ...formData, title: e.target.value })}
style={styles.input}
placeholder="Enter item title..."
/>
</div>
<div style={styles.formGroup}>
<label style={styles.label}>
<span style={{ color: '#666' }}>// </span>
Price ()
</label>
<input
type="number"
value={formData.price || ''}
onChange={(e) => setFormData({ ...formData, price: e.target.value ? Number(e.target.value) : undefined })}
style={styles.input}
placeholder="0"
/>
</div>
<div style={styles.formGroup}>
<label style={styles.label}>
<span style={{ color: '#666' }}>// </span>
Description
</label>
<textarea
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
style={styles.textarea}
placeholder="Enter description..."
/>
</div>
<div style={{ ...styles.formGroup, marginBottom: 0 }}>
<label style={styles.label}>
<span style={{ color: '#666' }}>// </span>
Note
</label>
<input
type="text"
value={formData.note}
onChange={(e) => setFormData({ ...formData, note: e.target.value })}
style={styles.input}
placeholder="Personal note..."
/>
</div>
</div>
</section>
{/* Images */}
<section style={styles.section}>
<div style={styles.sectionHeader}>
<span style={styles.sectionTitle}>
<span style={{ color: '#f87171' }}> </span>
images
<span style={{ color: '#facc15' }}> </span>
</span>
<button type="button" onClick={addImage} style={styles.btnAdd}>
[ + ADD ]
</button>
</div>
<div style={styles.sectionBody}>
{formData.images?.length === 0 && (
<div style={{ textAlign: 'center', padding: '16px', color: '#666' }}>
No images added
</div>
)}
{formData.images?.map((img, idx) => (
<div key={idx} style={styles.dynamicItem}>
<input
type="url"
placeholder="https://..."
value={img.url}
onChange={(e) => updateImage(idx, 'url', e.target.value)}
style={styles.inputFlex}
/>
<label style={styles.checkboxLabel}>
<input
type="checkbox"
checked={img.isMain}
onChange={(e) => updateImage(idx, 'isMain', e.target.checked)}
/>
Main
</label>
<button
type="button"
onClick={() => removeImage(idx)}
style={styles.btnRemove}
>
</button>
</div>
))}
</div>
</section>
{/* Links */}
<section style={styles.section}>
<div style={styles.sectionHeader}>
<span style={styles.sectionTitle}>
<span style={{ color: '#f87171' }}> </span>
links
<span style={{ color: '#facc15' }}> </span>
</span>
<button type="button" onClick={addLink} style={styles.btnAdd}>
[ + ADD ]
</button>
</div>
<div style={styles.sectionBody}>
{formData.links?.length === 0 && (
<div style={{ textAlign: 'center', padding: '16px', color: '#666' }}>
No links added
</div>
)}
{formData.links?.map((link, idx) => (
<div key={idx} style={styles.dynamicItem}>
<input
type="text"
placeholder="Title"
value={link.title}
onChange={(e) => updateLink(idx, 'title', e.target.value)}
style={styles.inputSmall}
/>
<input
type="url"
placeholder="https://..."
value={link.url}
onChange={(e) => updateLink(idx, 'url', e.target.value)}
style={styles.inputFlex}
/>
<label style={styles.checkboxLabel}>
<input
type="checkbox"
checked={link.isPrimary}
onChange={(e) => updateLink(idx, 'isPrimary', e.target.checked)}
/>
Primary
</label>
<button
type="button"
onClick={() => removeLink(idx)}
style={styles.btnRemove}
>
</button>
</div>
))}
</div>
</section>
{/* Submit */}
<div style={styles.formActions}>
<button
type="submit"
disabled={loading}
style={{
...styles.btnPrimary,
opacity: loading ? 0.5 : 1,
cursor: loading ? 'not-allowed' : 'pointer',
}}
>
{loading ? '[ CREATING... ]' : '[ CREATE ITEM ]'}
</button>
<button
type="button"
onClick={() => router.back()}
style={styles.btn}
>
[ CANCEL ]
</button>
</div>
</form>
);
}

View File

@@ -0,0 +1,222 @@
import type { WishlistItem as WishlistItemType } from '@home-service/contracts';
import Image from 'next/image';
interface Props {
item: WishlistItemType;
index: number;
}
const styles = {
card: {
background: '#111',
border: '1px solid #222',
marginBottom: '20px',
},
cardHeader: {
background: '#1a1a1a',
padding: '8px 12px',
borderBottom: '1px solid #222',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
},
cardTitle: {
color: '#22c55e',
fontWeight: 500,
},
cardId: {
color: '#666',
fontSize: '10px',
},
cardBody: {
display: 'flex',
flexDirection: 'row' as const,
gap: '20px',
padding: '16px',
},
imageBox: {
width: '120px',
height: '120px',
background: '#0a0a0a',
border: '1px dashed #222',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
},
content: {
flex: 1,
},
row: {
display: 'flex',
marginBottom: '8px',
},
label: {
color: '#22d3ee',
minWidth: '80px',
},
valueTitle: {
color: '#facc15',
fontWeight: 500,
},
valuePrice: {
color: '#22c55e',
fontWeight: 600,
},
valueDate: {
color: '#666',
},
desc: {
color: '#666',
padding: '8px',
background: '#0a0a0a',
borderLeft: '2px solid #e879f9',
margin: '12px 0',
},
note: {
padding: '8px',
background: '#0a0a0a',
borderLeft: '2px solid #60a5fa',
margin: '12px 0',
},
noteLabel: {
fontSize: '10px',
color: '#60a5fa',
marginBottom: '4px',
},
noteText: {
color: '#666',
fontStyle: 'italic' as const,
},
footer: {
padding: '12px',
borderTop: '1px solid #222',
background: '#0d0d0d',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
},
links: {
display: 'flex',
gap: '8px',
},
link: {
fontSize: '11px',
color: '#666',
textDecoration: 'none',
padding: '4px 10px',
border: '1px solid #222',
},
linkPrimary: {
fontSize: '11px',
textDecoration: 'none',
padding: '4px 10px',
background: '#22c55e',
border: '1px solid #22c55e',
color: '#000',
},
imagesCount: {
fontSize: '10px',
color: '#666',
},
};
export default function WishlistItem({ item, index }: Props) {
const mainImage = item.images.find((img) => img.isMain) || item.images[0];
const shortId = item.id.slice(0, 8);
const formatDate = (date: Date | string) => {
const d = new Date(date);
return d.toISOString().split('T')[0];
};
return (
<article id={`item-${item.id}`} style={styles.card}>
{/* Header */}
<div style={styles.cardHeader}>
<span style={styles.cardTitle}>
<span style={{ color: '#f87171' }}> </span>
item[{index}]
<span style={{ color: '#facc15' }}> </span>
</span>
<span style={styles.cardId}>#{shortId}</span>
</div>
{/* Body */}
<div style={styles.cardBody}>
{/* Image */}
<div style={styles.imageBox}>
{mainImage ? (
<Image
src={mainImage.url}
alt={item.title}
width={120}
height={120}
style={{ objectFit: 'cover', width: '100%', height: '100%' }}
unoptimized
/>
) : (
<span style={{ fontSize: '48px' }}>📦</span>
)}
</div>
{/* Content */}
<div style={styles.content}>
<div style={styles.row}>
<span style={styles.label}>title: </span>
<span style={styles.valueTitle}>{item.title}</span>
</div>
{item.price && (
<div style={styles.row}>
<span style={styles.label}>price: </span>
<span style={styles.valuePrice}>
{item.price.toLocaleString('ru-RU')}
</span>
</div>
)}
<div style={styles.row}>
<span style={styles.label}>added: </span>
<span style={styles.valueDate}>{formatDate(item.createdAt)}</span>
</div>
{item.description && (
<div style={styles.desc}>{item.description}</div>
)}
{item.note && (
<div style={styles.note}>
<div style={styles.noteLabel}>📝 note</div>
<p style={styles.noteText}>{item.note}</p>
</div>
)}
</div>
</div>
{/* Footer */}
{item.links.length > 0 && (
<div style={styles.footer}>
<div style={styles.links}>
{item.links.map((link) => (
<a
key={link.id}
href={link.url}
target="_blank"
rel="noopener noreferrer"
style={link.isPrimary ? styles.linkPrimary : styles.link}
>
[{link.title.toLowerCase()}]
</a>
))}
</div>
{item.images.length > 0 && (
<span style={styles.imagesCount}>
images: {item.images.length}
</span>
)}
</div>
)}
</article>
);
}

47
frontend/src/lib/api.ts Normal file
View File

@@ -0,0 +1,47 @@
import type { WishlistItem, CreateWishlistItem, UpdateWishlistItem } from '@home-service/contracts';
// Server-side uses API_URL (internal Docker network), client uses NEXT_PUBLIC_API_URL
const API_URL = typeof window === 'undefined'
? (process.env.API_URL || process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000')
: (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000');
export const wishlistApi = {
async getAll(): Promise<WishlistItem[]> {
const res = await fetch(`${API_URL}/wishlist`, { cache: 'no-store' });
if (!res.ok) throw new Error('Failed to fetch wishlist');
return res.json();
},
async getOne(id: string): Promise<WishlistItem> {
const res = await fetch(`${API_URL}/wishlist/${id}`, { cache: 'no-store' });
if (!res.ok) throw new Error('Failed to fetch item');
return res.json();
},
async create(data: CreateWishlistItem): Promise<WishlistItem> {
const res = await fetch(`${API_URL}/wishlist`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!res.ok) throw new Error('Failed to create item');
return res.json();
},
async update(id: string, data: UpdateWishlistItem): Promise<WishlistItem> {
const res = await fetch(`${API_URL}/wishlist/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (!res.ok) throw new Error('Failed to update item');
return res.json();
},
async delete(id: string): Promise<void> {
const res = await fetch(`${API_URL}/wishlist/${id}`, {
method: 'DELETE',
});
if (!res.ok) throw new Error('Failed to delete item');
},
};

View File

@@ -0,0 +1,25 @@
import type { Config } from 'tailwindcss';
const config: Config = {
content: [
'./src/pages/**/*.{js,ts,jsx,tsx,mdx}',
'./src/components/**/*.{js,ts,jsx,tsx,mdx}',
'./src/app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {
colors: {
'term-bg': '#0a0a0a',
'term-green': '#00ff41',
'term-dim': '#008f11',
'term-dark': '#0d0208',
},
fontFamily: {
mono: ['"Courier New"', 'Courier', 'monospace'],
},
},
},
plugins: [],
};
export default config;

View File

@@ -0,0 +1,430 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Panel — Terminal Style</title>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0c0c0c;
--bg-card: #111;
--bg-input: #0a0a0a;
--border: #222;
--text: #c0c0c0;
--text-dim: #666;
--green: #22c55e;
--cyan: #22d3ee;
--yellow: #facc15;
--magenta: #e879f9;
--blue: #60a5fa;
--red: #f87171;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'JetBrains Mono', monospace;
background: var(--bg);
color: var(--text);
line-height: 1.6;
font-size: 13px;
min-height: 100vh;
padding: 40px;
}
.container {
max-width: 800px;
margin: 0 auto;
}
/* Header */
.header {
background: var(--bg-card);
border: 1px solid var(--border);
padding: 20px 24px;
margin-bottom: 24px;
display: flex;
justify-content: space-between;
align-items: center;
}
.header-title {
font-size: 20px;
font-weight: 600;
color: var(--green);
}
.header-title::before {
content: "> ";
color: var(--text-dim);
}
.header-subtitle {
font-size: 11px;
color: var(--text-dim);
margin-top: 4px;
}
.header-back {
font-size: 11px;
color: var(--text-dim);
text-decoration: none;
padding: 6px 12px;
border: 1px solid var(--border);
transition: all 0.1s;
}
.header-back:hover {
border-color: var(--cyan);
color: var(--cyan);
}
/* Form Section */
.form-section {
background: var(--bg-card);
border: 1px solid var(--border);
margin-bottom: 20px;
}
.form-section-header {
background: #1a1a1a;
padding: 12px 16px;
border-bottom: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
}
.form-section-title {
color: var(--green);
font-weight: 500;
}
.form-section-title::before {
content: "● ";
color: var(--red);
}
.form-section-title::after {
content: " ●";
color: var(--yellow);
}
.form-section-body {
padding: 20px;
}
/* Form Fields */
.form-group {
margin-bottom: 16px;
}
.form-group:last-child {
margin-bottom: 0;
}
.form-label {
display: block;
color: var(--cyan);
font-size: 11px;
margin-bottom: 6px;
}
.form-label::before {
content: "// ";
color: var(--text-dim);
}
.form-label .required {
color: var(--red);
}
.form-input,
.form-textarea {
width: 100%;
background: var(--bg-input);
border: 1px solid var(--border);
padding: 10px 12px;
color: var(--green);
font-family: inherit;
font-size: 13px;
outline: none;
transition: border-color 0.1s;
}
.form-input:focus,
.form-textarea:focus {
border-color: var(--green);
}
.form-input::placeholder,
.form-textarea::placeholder {
color: var(--text-dim);
}
.form-textarea {
resize: vertical;
min-height: 80px;
}
.form-row {
display: flex;
gap: 16px;
}
.form-row .form-group {
flex: 1;
}
/* Dynamic Items (Images, Links) */
.dynamic-item {
display: flex;
gap: 8px;
align-items: center;
margin-bottom: 12px;
padding: 12px;
background: var(--bg-input);
border: 1px dashed var(--border);
}
.dynamic-item .form-input {
flex: 1;
}
.dynamic-item .form-input.small {
width: 120px;
flex: none;
}
.checkbox-label {
display: flex;
align-items: center;
gap: 6px;
color: var(--text-dim);
font-size: 11px;
white-space: nowrap;
cursor: pointer;
}
.checkbox-label input[type="checkbox"] {
accent-color: var(--green);
}
.btn-remove {
background: none;
border: none;
color: var(--red);
cursor: pointer;
padding: 4px 8px;
font-size: 14px;
}
.btn-remove:hover {
color: #ef4444;
}
.btn-add {
font-size: 11px;
color: var(--text-dim);
text-decoration: none;
padding: 4px 10px;
border: 1px solid var(--border);
background: none;
cursor: pointer;
transition: all 0.1s;
}
.btn-add:hover {
border-color: var(--green);
color: var(--green);
}
/* Buttons */
.form-actions {
display: flex;
gap: 12px;
margin-top: 24px;
}
.btn {
flex: 1;
padding: 12px 20px;
font-family: inherit;
font-size: 12px;
border: 1px solid var(--border);
background: none;
color: var(--text-dim);
cursor: pointer;
transition: all 0.1s;
text-align: center;
}
.btn:hover {
border-color: var(--cyan);
color: var(--cyan);
}
.btn-primary {
background: var(--green);
border-color: var(--green);
color: #000;
}
.btn-primary:hover {
background: #16a34a;
color: #fff;
}
/* Error Message */
.error-message {
background: rgba(248, 113, 113, 0.1);
border: 1px solid var(--red);
color: var(--red);
padding: 12px 16px;
margin-bottom: 20px;
}
.error-message::before {
content: "ERROR: ";
font-weight: 600;
}
/* Empty State */
.empty-state {
text-align: center;
padding: 24px;
color: var(--text-dim);
}
</style>
</head>
<body>
<div class="container">
<!-- Header -->
<header class="header">
<div>
<h1 class="header-title">ADMIN_PANEL<span style="animation: blink 1s step-end infinite;">_</span></h1>
<p class="header-subtitle">// Create new wishlist item</p>
</div>
<a href="wishlist-mockup.html" class="header-back">[ ← BACK TO LIST ]</a>
</header>
<!-- Error (hidden by default) -->
<!-- <div class="error-message">Something went wrong</div> -->
<form>
<!-- Basic Info -->
<section class="form-section">
<div class="form-section-header">
<span class="form-section-title">basic_info</span>
</div>
<div class="form-section-body">
<div class="form-group">
<label class="form-label">Title <span class="required">*</span></label>
<input type="text" class="form-input" placeholder="Enter item title..." required>
</div>
<div class="form-row">
<div class="form-group">
<label class="form-label">Price (₽)</label>
<input type="number" class="form-input" placeholder="0">
</div>
</div>
<div class="form-group">
<label class="form-label">Description</label>
<textarea class="form-textarea" placeholder="Enter description..."></textarea>
</div>
<div class="form-group">
<label class="form-label">Note</label>
<input type="text" class="form-input" placeholder="Personal note...">
</div>
</div>
</section>
<!-- Images -->
<section class="form-section">
<div class="form-section-header">
<span class="form-section-title">images</span>
<button type="button" class="btn-add">[ + ADD ]</button>
</div>
<div class="form-section-body">
<div class="dynamic-item">
<input type="url" class="form-input" placeholder="https://example.com/image.jpg">
<label class="checkbox-label">
<input type="checkbox"> Main
</label>
<button type="button" class="btn-remove"></button>
</div>
<div class="dynamic-item">
<input type="url" class="form-input" placeholder="https://example.com/image2.jpg">
<label class="checkbox-label">
<input type="checkbox" checked> Main
</label>
<button type="button" class="btn-remove"></button>
</div>
<!-- Empty state example -->
<!-- <div class="empty-state">No images added</div> -->
</div>
</section>
<!-- Links -->
<section class="form-section">
<div class="form-section-header">
<span class="form-section-title">links</span>
<button type="button" class="btn-add">[ + ADD ]</button>
</div>
<div class="form-section-body">
<div class="dynamic-item">
<input type="text" class="form-input small" placeholder="Title">
<input type="url" class="form-input" placeholder="https://ozon.ru/...">
<label class="checkbox-label">
<input type="checkbox" checked> Primary
</label>
<button type="button" class="btn-remove"></button>
</div>
<div class="dynamic-item">
<input type="text" class="form-input small" placeholder="Title">
<input type="url" class="form-input" placeholder="https://...">
<label class="checkbox-label">
<input type="checkbox"> Primary
</label>
<button type="button" class="btn-remove"></button>
</div>
</div>
</section>
<!-- Actions -->
<div class="form-actions">
<button type="submit" class="btn btn-primary">[ CREATE ITEM ]</button>
<button type="button" class="btn">[ CANCEL ]</button>
</div>
</form>
</div>
<style>
@keyframes blink {
0%,
100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
</style>
</body>
</html>

View File

@@ -0,0 +1,525 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wishlist — Terminal Style</title>
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0c0c0c;
--bg-card: #111;
--border: #222;
--text: #c0c0c0;
--text-dim: #666;
--green: #22c55e;
--cyan: #22d3ee;
--yellow: #facc15;
--magenta: #e879f9;
--blue: #60a5fa;
--red: #f87171;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'JetBrains Mono', monospace;
background: var(--bg);
color: var(--text);
line-height: 1.6;
font-size: 13px;
}
.layout {
min-height: 100vh;
}
/* SIDEBAR - FLOATING LEFT */
.sidebar {
width: 220px;
background: var(--bg);
border-right: 1px solid var(--border);
padding: 20px 16px;
position: fixed;
left: 0;
top: 0;
height: 100vh;
overflow-y: auto;
z-index: 100;
}
.sidebar-header {
margin-bottom: 24px;
padding-bottom: 16px;
border-bottom: 1px dashed var(--border);
}
.sidebar-header h1 {
font-size: 14px;
font-weight: 600;
color: var(--green);
}
.sidebar-header h1::before {
content: "$ ";
color: var(--text-dim);
}
.sidebar-header p {
font-size: 11px;
color: var(--text-dim);
margin-top: 4px;
}
.sidebar-header p::before {
content: "# ";
color: var(--text-dim);
}
.nav-section {
margin-bottom: 20px;
}
.nav-title {
font-size: 11px;
color: var(--cyan);
margin-bottom: 8px;
}
.nav-title::before {
content: "── ";
color: var(--text-dim);
}
.nav-title::after {
content: " ──────";
color: var(--text-dim);
}
.nav-item {
display: block;
padding: 4px 0;
padding-left: 16px;
color: var(--text-dim);
text-decoration: none;
font-size: 12px;
transition: color 0.1s ease;
border-left: 2px solid transparent;
}
.nav-item::before {
content: "├─ ";
color: var(--text-dim);
}
.nav-item:last-child::before {
content: "└─ ";
}
.nav-item:hover {
color: var(--green);
}
.nav-item.active {
color: var(--green);
border-left-color: var(--green);
}
/* MAIN - CENTERED */
.main {
max-width: 800px;
margin: 0 auto;
padding: 40px 32px;
}
.page-header {
margin-bottom: 32px;
padding-bottom: 16px;
border-bottom: 1px solid var(--border);
}
.page-header h2 {
font-size: 16px;
font-weight: 600;
color: var(--yellow);
}
.page-header h2::before {
content: "┌── ";
color: var(--text-dim);
}
.page-header p {
color: var(--text-dim);
font-size: 12px;
margin-top: 8px;
padding-left: 4px;
}
.page-header p::before {
content: "│ ";
color: var(--text-dim);
}
/* CARDS - TERMINAL STYLE */
.card {
background: var(--bg-card);
border: 1px solid var(--border);
margin-bottom: 20px;
font-size: 12px;
}
.card-top {
background: #1a1a1a;
padding: 8px 12px;
border-bottom: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
}
.card-top-title {
color: var(--green);
font-weight: 500;
}
.card-top-title::before {
content: "● ";
color: var(--red);
}
.card-top-title::after {
content: " ●";
color: var(--yellow);
}
.card-top-id {
color: var(--text-dim);
font-size: 10px;
}
.card-body {
padding: 16px;
display: flex;
gap: 20px;
}
.card-image {
width: 120px;
height: 120px;
background: #0a0a0a;
border: 1px dashed var(--border);
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
font-size: 48px;
}
.card-content {
flex: 1;
}
.card-row {
margin-bottom: 8px;
display: flex;
}
.card-label {
color: var(--cyan);
min-width: 80px;
}
.card-label::after {
content: ": ";
}
.card-value {
color: var(--text);
}
.card-value.price {
color: var(--green);
font-weight: 600;
}
.card-value.title {
color: var(--yellow);
font-weight: 500;
}
.card-value.date {
color: var(--text-dim);
}
.card-desc {
color: var(--text-dim);
margin: 12px 0;
padding: 8px;
background: #0a0a0a;
border-left: 2px solid var(--magenta);
}
.card-note {
margin: 12px 0;
padding: 8px;
background: #0a0a0a;
border-left: 2px solid var(--blue);
}
.card-note-label {
font-size: 10px;
color: var(--blue);
margin-bottom: 4px;
}
.card-note-label::before {
content: "📝 ";
}
.card-note-text {
color: var(--text-dim);
font-style: italic;
}
.card-footer {
padding: 12px 16px;
border-top: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
background: #0d0d0d;
}
.card-links {
display: flex;
gap: 8px;
}
.card-link {
font-size: 11px;
color: var(--text-dim);
text-decoration: none;
padding: 4px 10px;
border: 1px solid var(--border);
transition: all 0.1s ease;
}
.card-link:hover {
border-color: var(--cyan);
color: var(--cyan);
}
.card-link.primary {
background: var(--green);
border-color: var(--green);
color: #000;
}
.card-link.primary:hover {
background: #16a34a;
}
.card-images-count {
font-size: 10px;
color: var(--text-dim);
}
</style>
</head>
<body>
<div class="layout">
<!-- SIDEBAR -->
<aside class="sidebar">
<div class="sidebar-header">
<h1>wishlist</h1>
<p>v1.0.0</p>
</div>
<nav class="nav-section">
<div class="nav-title">items</div>
<a href="#item-1" class="nav-item active">Sony WH-1000XM5</a>
<a href="#item-2" class="nav-item">Kindle Paperwhite</a>
<a href="#item-3" class="nav-item">Keychron K2 Pro</a>
<a href="#item-4" class="nav-item">Audio-Technica</a>
</nav>
</aside>
<!-- MAIN CONTENT -->
<main class="main">
<header class="page-header">
<h2>wishlist --list</h2>
<p>Найдено 4 элементов в списке желаний</p>
</header>
<div class="cards">
<!-- Card 1 -->
<article class="card" id="item-1">
<div class="card-top">
<span class="card-top-title">item[0]</span>
<span class="card-top-id">#a1b2c3d4</span>
</div>
<div class="card-body">
<div class="card-image">🎧</div>
<div class="card-content">
<div class="card-row">
<span class="card-label">title</span>
<span class="card-value title">Sony WH-1000XM5</span>
</div>
<div class="card-row">
<span class="card-label">price</span>
<span class="card-value price">35,000 ₽</span>
</div>
<div class="card-row">
<span class="card-label">added</span>
<span class="card-value date">2024-12-05</span>
</div>
<div class="card-desc">
Беспроводные наушники с лучшим в классе активным шумоподавлением, 30 часов автономной
работы.
</div>
<div class="card-note">
<div class="card-note-label">note</div>
<p class="card-note-text">Хочу чёрный цвет. Можно б/у в хорошем состоянии.</p>
</div>
</div>
</div>
<div class="card-footer">
<div class="card-links">
<a href="#" class="card-link primary">[ozon]</a>
<a href="#" class="card-link">[yandex]</a>
<a href="#" class="card-link">[mvideo]</a>
</div>
<span class="card-images-count">images: 3</span>
</div>
</article>
<!-- Card 2 -->
<article class="card" id="item-2">
<div class="card-top">
<span class="card-top-title">item[1]</span>
<span class="card-top-id">#e5f6g7h8</span>
</div>
<div class="card-body">
<div class="card-image">📖</div>
<div class="card-content">
<div class="card-row">
<span class="card-label">title</span>
<span class="card-value title">Kindle Paperwhite</span>
</div>
<div class="card-row">
<span class="card-label">price</span>
<span class="card-value price">18,000 ₽</span>
</div>
<div class="card-row">
<span class="card-label">added</span>
<span class="card-value date">2024-12-02</span>
</div>
<div class="card-desc">
Электронная книга с E-Ink дисплеем 6.8", тёплой подсветкой и водозащитой IPX8.
</div>
<div class="card-note">
<div class="card-note-label">note</div>
<p class="card-note-text">Signature Edition с беспроводной зарядкой — идеально.</p>
</div>
</div>
</div>
<div class="card-footer">
<div class="card-links">
<a href="#" class="card-link primary">[amazon]</a>
<a href="#" class="card-link">[aliexpress]</a>
</div>
<span class="card-images-count">images: 2</span>
</div>
</article>
<!-- Card 3 -->
<article class="card" id="item-3">
<div class="card-top">
<span class="card-top-title">item[2]</span>
<span class="card-top-id">#i9j0k1l2</span>
</div>
<div class="card-body">
<div class="card-image">⌨️</div>
<div class="card-content">
<div class="card-row">
<span class="card-label">title</span>
<span class="card-value title">Keychron K2 Pro</span>
</div>
<div class="card-row">
<span class="card-label">price</span>
<span class="card-value price">12,000 ₽</span>
</div>
<div class="card-row">
<span class="card-label">added</span>
<span class="card-value date">2024-11-28</span>
</div>
<div class="card-desc">
Беспроводная механическая клавиатура 75% с hot-swap, RGB и Gateron Brown.
</div>
<div class="card-note">
<div class="card-note-label">note</div>
<p class="card-note-text">Нужна версия с ISO раскладкой. Цвет — тёмно-серый.</p>
</div>
</div>
</div>
<div class="card-footer">
<div class="card-links">
<a href="#" class="card-link primary">[keychron]</a>
<a href="#" class="card-link">[wildberries]</a>
</div>
<span class="card-images-count">images: 4</span>
</div>
</article>
<!-- Card 4 -->
<article class="card" id="item-4">
<div class="card-top">
<span class="card-top-title">item[3]</span>
<span class="card-top-id">#m3n4o5p6</span>
</div>
<div class="card-body">
<div class="card-image">🎵</div>
<div class="card-content">
<div class="card-row">
<span class="card-label">title</span>
<span class="card-value title">Audio-Technica AT-LP60X</span>
</div>
<div class="card-row">
<span class="card-label">price</span>
<span class="card-value price">20,000 ₽</span>
</div>
<div class="card-row">
<span class="card-label">added</span>
<span class="card-value date">2024-11-15</span>
</div>
<div class="card-desc">
Проигрыватель виниловых пластинок. Автоматический, встроенный фонокорректор.
</div>
<div class="card-note">
<div class="card-note-label">note</div>
<p class="card-note-text">Хочу в подарок пластинку Pink Floyd — The Dark Side of the
Moon 🌙</p>
</div>
</div>
</div>
<div class="card-footer">
<div class="card-links">
<a href="#" class="card-link primary">[dns]</a>
<a href="#" class="card-link">[citilink]</a>
<a href="#" class="card-link">[avito]</a>
</div>
<span class="card-images-count">images: 1</span>
</div>
</article>
</div>
</main>
</div>
</body>
</html>

View File

@@ -1,7 +1,11 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2017", "target": "ES2021",
"lib": ["dom", "dom.iterable", "esnext"], "lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"strict": true, "strict": true,
@@ -19,7 +23,9 @@
} }
], ],
"paths": { "paths": {
"@/*": ["./src/*"] "@/*": [
"./src/*"
]
} }
}, },
"include": [ "include": [
@@ -27,8 +33,9 @@
"**/*.ts", "**/*.ts",
"**/*.tsx", "**/*.tsx",
".next/types/**/*.ts", ".next/types/**/*.ts",
".next/dev/types/**/*.ts", ".next/dev/types/**/*.ts"
"**/*.mts"
], ],
"exclude": ["node_modules"] "exclude": [
"node_modules"
]
} }

View File

@@ -9,7 +9,9 @@
"lint": "turbo lint", "lint": "turbo lint",
"format": "turbo format", "format": "turbo format",
"test": "turbo test", "test": "turbo test",
"clean": "turbo clean && rm -rf node_modules" "clean": "turbo clean && rm -rf node_modules",
"db:generate": "pnpm --filter @home-service/backend db:generate",
"db:migrate": "pnpm --filter @home-service/backend db:migrate"
}, },
"devDependencies": { "devDependencies": {
"turbo": "^2.3.3" "turbo": "^2.3.3"

3383
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,3 +1,4 @@
packages: packages:
- 'admin' - 'frontend'
- 'backend' - 'backend'
- 'contracts'

View File

@@ -1,6 +1,6 @@
{ {
"$schema": "https://turbo.build/schema.json", "$schema": "https://turbo.build/schema.json",
"ui": "stream", "ui": "tui",
"tasks": { "tasks": {
"build": { "build": {
"dependsOn": [ "dependsOn": [