Compare commits

..
20 changed files with 625 additions and 115 deletions

No files matched your search

+18 -4
View File
@@ -1,6 +1,6 @@
# Family Wishlist
A small, private wishlist app for two users. Each user has their own profile, slug, and independent wishlist. Guests see a public page at `/u/<slug>` and can view active and fulfilled wishes.
A small, private wishlist app for two users. The signed-in dashboard shows both users' active and fulfilled wishes, with filters for each author and shared folders. Each user also has a public profile at `/u/<slug>` with their own active and fulfilled wishes.
- **Backend**: Node.js 20, Fastify 4, Prisma 5, PostgreSQL 16
- **Frontend**: React 18, Vite 5, Tailwind CSS, TanStack Query, React Hook Form + Zod
@@ -12,6 +12,7 @@ A small, private wishlist app for two users. Each user has their own profile, sl
## Features
- Two fixed accounts (credentials in env), password stored only as a **bcrypt hash**.
- Either user can create a shared folder with an optional description and emoji or image cover, and add their own wishes to any shared folder. Each wish also appears in its author's list.
- Wish entity: title, price, currency, link, comment, image (auto-fetched from link or uploaded).
- Statuses: **Active → Archive / Fulfilled → Trash** (kept for 30 days, then permanently removed by a daily cron job).
- Restore from archive or trash. Duplicate from fulfilled into a new active wish.
@@ -59,7 +60,8 @@ utils/ errors, bcrypt helpers, version helper
See `apps/backend/prisma/schema.prisma`. Tables:
- `User` — `id`, `username`, `slug`, `displayName`, `bio`, `avatarUrl`. **No password hash.**
- `Wish` — `userId`, `title`, `price`, `currency`, `url`, `comment`, `imageUrl`, `imageSource`, `status`, timestamps, `sourceWishId` (for duplicates).
- `Wish` — `userId`, optional `folderId`, `title`, `price`, `currency`, `url`, `comment`, `imageUrl`, `imageSource`, `status`, timestamps, `sourceWishId` (for duplicates).
- `WishFolder` — shared folder metadata and its creator.
- `GuestView` — `(guestId, wishId)` pairs for "already seen" tracking.
### Password storage
@@ -156,6 +158,16 @@ On first start, the backend:
3. Starts Fastify on port 3000.
4. Registers the daily trash-purge cron (runs at 03:17 UTC, also once on startup).
### Production release
Follow the [controlled deployment runbook in infra-home](https://git.vakanaut.ru/admin/infra-home/src/branch/main/docs/runbooks/deployment.md). Build the frontend and backend images from the same merged revision and record both image digests. Release the pair together because the 0.4.0 home page uses the new `/api/dashboard` endpoint.
Before upgrading an existing deployment, back up PostgreSQL and the uploads volume. Verify that the backup can be restored in an isolated environment. After deployment, check `/api/health`, `/api/version` and the signed-in dashboard. Confirm that an existing wish is still visible and a new wish in a shared folder also appears in the author's folder.
If a rollback is needed, restore the previous frontend and backend images together. For a pre-0.4.0 backend image, override the command with `node dist/src/index.js` (from `/app/apps/backend`). The previous image's default startup runs `prisma db push --accept-data-loss`, which can remove the shared folder table and wish-to-folder links.
### Development schema migrations
> For a stricter migration workflow, switch to `prisma migrate dev` locally to produce
> versioned migration files and change the Docker `CMD` to `prisma migrate deploy`.
@@ -203,6 +215,8 @@ All responses are JSON. Authenticated endpoints require the `fw_auth` cookie.
| GET | `/api/auth/me` | owner | Current user. |
| GET | `/api/profile` | owner | Own profile. |
| PATCH | `/api/profile` | owner | Update slug/displayName/bio/avatar. |
| GET | `/api/dashboard` | signed in | Shared folders, authors, and active and fulfilled wishes from both accounts. |
| POST | `/api/folders` | signed in | Create a shared folder. Multipart fields: `name`, optional `description`, and optional `emoji` or `cover` file. |
| GET | `/api/wishes?status=active\|archived\|completed\|deleted` | owner | List own wishes. |
| POST | `/api/wishes` | owner | Create. |
| GET | `/api/wishes/:id` | owner | Get own wish. |
@@ -227,7 +241,7 @@ All responses are JSON. Authenticated endpoints require the `fw_auth` cookie.
Each package has its own version (`apps/backend/package.json` and `apps/frontend/package.json`). The app footer shows both:
```
frontend v0.3.4 · backend v0.3.0
frontend v0.4.0 · backend v0.4.0
```
Bump them per semver on each change:
@@ -240,7 +254,7 @@ Bump them per semver on each change:
## Security notes
- Cookies are `httpOnly`, `SameSite=Lax`, `Secure` in production.
- All auth-scoped routes re-check ownership in the service layer (`userId` vs `req.user.id`).
- Wish mutations check ownership in the service layer (`userId` vs `req.user.id`). The shared dashboard requires a signed-in account.
- `/api/auth/login` is rate-limited; username enumeration is mitigated by a constant-time dummy compare.
- Image fetcher has a 10s timeout, a 5 MB cap, and accepts only `image/jpeg|png|webp|gif`.
- Multipart upload cap: 8 MB, one file per request.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/backend",
"version": "0.3.0",
"version": "0.4.0",
"private": true,
"type": "module",
"main": "dist/index.js",
+16
View File
@@ -28,6 +28,19 @@ model User {
updatedAt DateTime @updatedAt
wishes Wish[]
folders WishFolder[]
}
model WishFolder {
id String @id @default(cuid())
name String
description String?
emoji String?
imageUrl String?
creatorId String
creator User @relation(fields: [creatorId], references: [id])
createdAt DateTime @default(now())
wishes Wish[]
}
enum WishStatus {
@@ -61,12 +74,15 @@ model Wish {
completedAt DateTime?
deletedAt DateTime?
sourceWishId String?
folderId String?
folder WishFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)
views GuestView[]
@@index([userId, status])
@@index([deletedAt])
@@index([createdAt])
@@index([folderId])
}
model GuestView {
+2
View File
@@ -16,6 +16,7 @@ import multipartPlugin from './plugins/multipart.js';
import authRoutes from './modules/auth/auth.routes.js';
import profileRoutes from './modules/profile/profile.routes.js';
import wishesRoutes from './modules/wishes/wishes.routes.js';
import dashboardRoutes from './modules/wishes/dashboard.routes.js';
import imagesRoutes from './modules/images/images.routes.js';
import publicRoutes from './modules/public/public.routes.js';
import metaRoutes from './modules/meta/meta.routes.js';
@@ -77,6 +78,7 @@ export async function buildApp(): Promise<FastifyInstance> {
await app.register(authRoutes, { prefix: '/api/auth' });
await app.register(profileRoutes, { prefix: '/api/profile' });
await app.register(wishesRoutes, { prefix: '/api/wishes' });
await app.register(dashboardRoutes, { prefix: '/api' });
await app.register(imagesRoutes, { prefix: '/api/wishes' });
await app.register(publicRoutes, { prefix: '/api/public' });
@@ -31,7 +31,7 @@ export default async function publicRoutes(app: FastifyInstance) {
})
: [];
const seenSet = new Set(seen.map((s) => s.wishId));
return wishes.map((w) => ({
return wishes.map(({ folderId: _folderId, ...w }) => ({
...w,
isNewForGuest: w.status === 'ACTIVE' && !seenSet.has(w.id),
}));
@@ -0,0 +1,100 @@
import { randomUUID } from 'node:crypto';
import type { FastifyInstance } from 'fastify';
import { createFolderSchema, NEW_BADGE_DAYS } from '@family-wishlist/shared';
import { usersRegistry } from '../../auth/users.registry.js';
import { MAX_UPLOAD_BYTES } from '../../plugins/multipart.js';
import { UnauthorizedError, ValidationError } from '../../utils/errors.js';
import { deleteLocalImageIfAny, saveUploadedImage } from '../images/storage.service.js';
const folderFields = ['name', 'description', 'emoji'];
export default async function dashboardRoutes(app: FastifyInstance) {
app.addHook('preHandler', async (request) => {
await app.authenticate(request);
if (!usersRegistry.findById(request.user.id)) throw new UnauthorizedError();
});
app.get('/dashboard', async (_request, reply) => {
const authorIds = usersRegistry.all().map((user) => user.id);
const [users, folders, wishes] = await Promise.all([
app.prisma.user.findMany({
where: { id: { in: authorIds } },
select: { id: true, displayName: true, avatarUrl: true },
}),
app.prisma.wishFolder.findMany({
select: { id: true, name: true, description: true, emoji: true, imageUrl: true },
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
}),
app.prisma.wish.findMany({
where: { userId: { in: authorIds }, status: { in: ['ACTIVE', 'COMPLETED'] } },
orderBy: [{ status: 'asc' }, { createdAt: 'desc' }, { id: 'asc' }],
}),
]);
const newSince = Date.now() - NEW_BADGE_DAYS * 24 * 60 * 60 * 1000;
reply.header('Cache-Control', 'private, no-store');
return {
authors: users.sort((a, b) => authorIds.indexOf(a.id) - authorIds.indexOf(b.id)),
folders,
wishes: wishes.map((wish) => ({
...wish,
isNewForOwner: wish.status === 'ACTIVE' && wish.createdAt.getTime() > newSince,
})),
};
});
app.post('/folders', async (request, reply) => {
if (!request.isMultipart()) throw new ValidationError('Expected form data');
const fields: Record<string, unknown> = {};
let cover: { mime: string; buffer: Buffer } | undefined;
try {
for await (const part of request.parts({
limits: { files: 1, fields: 3, fieldSize: 4096, fileSize: MAX_UPLOAD_BYTES },
})) {
if (part.type === 'file') {
const buffer = await part.toBuffer();
if (part.fieldname !== 'cover' || part.file.truncated || !buffer.length) {
throw new ValidationError('Invalid cover');
}
cover = { mime: part.mimetype, buffer };
} else if (folderFields.includes(part.fieldname) && !part.valueTruncated) {
fields[part.fieldname] = part.value;
} else {
throw new ValidationError('Invalid folder field');
}
}
} catch (error) {
if (error instanceof app.multipartErrors.RequestFileTooLargeError) {
throw new ValidationError('File too large');
}
if (error instanceof app.multipartErrors.FilesLimitError ||
error instanceof app.multipartErrors.FieldsLimitError) {
throw new ValidationError('Invalid folder form');
}
throw error;
}
const input = createFolderSchema.parse(fields);
if (input.emoji && cover) throw new ValidationError('Choose one cover type');
const imageUrl = cover
? (await saveUploadedImage(`folder-${randomUUID()}`, cover.mime, cover.buffer)).imageUrl
: null;
try {
const folder = await app.prisma.wishFolder.create({
data: {
name: input.name,
description: input.description || null,
emoji: input.emoji || null,
imageUrl,
creatorId: request.user.id,
},
select: { id: true, name: true, description: true, emoji: true, imageUrl: true },
});
reply.code(201);
return folder;
} catch (error) {
await deleteLocalImageIfAny(imageUrl);
throw error;
}
});
}
@@ -32,10 +32,18 @@ export class WishesService {
return wish;
}
create(userId: string, input: CreateWishInput): Promise<Wish> {
private async checkFolder(folderId: string | null | undefined): Promise<void> {
if (folderId && !(await this.prisma.wishFolder.findUnique({ where: { id: folderId } }))) {
throw new NotFoundError('Folder');
}
}
async create(userId: string, input: CreateWishInput): Promise<Wish> {
await this.checkFolder(input.folderId);
return this.prisma.wish.create({
data: {
userId,
folderId: input.folderId,
title: input.title,
price: input.price ?? null,
currency: input.currency ?? 'RUB',
@@ -47,7 +55,9 @@ export class WishesService {
async update(userId: string, id: string, input: UpdateWishInput): Promise<Wish> {
await this.getOwned(userId, id);
await this.checkFolder(input.folderId);
const data: Record<string, unknown> = {};
if (input.folderId !== undefined) data.folderId = input.folderId;
if (input.title !== undefined) data.title = input.title;
if (input.price !== undefined) data.price = input.price ?? null;
if (input.currency !== undefined) data.currency = input.currency ?? 'RUB';
@@ -111,6 +121,7 @@ export class WishesService {
imageUrl: source.imageSource === 'UPLOADED' ? null : source.imageUrl,
imageSource: source.imageSource === 'UPLOADED' ? 'DEFAULT' : source.imageSource,
sourceWishId: source.id,
folderId: source.folderId,
},
});
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/frontend",
"version": "0.3.4",
"version": "0.4.0",
"private": true,
"type": "module",
"scripts": {
@@ -1,5 +1,5 @@
import { Link, NavLink, useNavigate } from 'react-router-dom';
import { Archive, CheckCircle2, Gift, LogOut, Sparkles, Trash2, UserCog, Users } from 'lucide-react';
import { Archive, CheckCircle2, Gift, House, LogOut, Trash2, UserCog, Users } from 'lucide-react';
import type { ComponentType } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '../ui/Button';
@@ -18,7 +18,7 @@ interface FriendProfile {
}
const links = [
{ to: '/', label: 'header.active', icon: Sparkles, end: true },
{ to: '/', label: 'header.home', icon: House, end: true },
{ to: '/completed', label: 'header.fulfilled', icon: CheckCircle2 },
{ to: '/archive', label: 'header.archive', icon: Archive },
{ to: '/trash', label: 'header.trash', icon: Trash2 },
@@ -0,0 +1,107 @@
import { useState, type FormEvent } from 'react';
import { createFolderSchema, type WishFolder } from '@family-wishlist/shared';
import { FolderPlus } from 'lucide-react';
import { useCreateFolder } from '@/features/wishes/wishes.hooks';
import { useI18n } from '@/i18n/i18n';
import { Button } from '../ui/Button';
import { Input } from '../ui/Input';
import { Label } from '../ui/Label';
import { Textarea } from '../ui/Textarea';
const coverTypes = 'image/jpeg,image/png,image/webp,image/gif';
export function FolderForm({
onCancel,
onCreated,
}: {
onCancel: () => void;
onCreated: (folder: WishFolder) => void;
}) {
const { t } = useI18n();
const create = useCreateFolder();
const [coverType, setCoverType] = useState<'none' | 'emoji' | 'image'>('none');
const [error, setError] = useState<string>();
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (create.isPending) return;
const form = new FormData(event.currentTarget);
const input = createFolderSchema.safeParse({
name: form.get('name'),
description: form.get('description'),
emoji: form.get('emoji') ?? undefined,
});
const file = form.get('cover');
const cover = file instanceof File && file.size > 0 ? file : null;
if (!input.success) {
const errors = input.error.flatten().fieldErrors;
setError(t(errors.emoji ? 'folders.invalidEmoji' : 'folders.invalidDetails'));
return;
}
if (coverType === 'image' && (!cover || !coverTypes.split(',').includes(cover.type) ||
cover.size > 8 * 1024 * 1024)) {
setError(t('folders.invalidImage'));
return;
}
setError(undefined);
try {
onCreated(await create.mutateAsync({ input: input.data, cover }));
} catch {
setError(t('folders.saveError'));
}
}
return (
<form className="wish-folders__form" onSubmit={submit} aria-busy={create.isPending}>
<div className="field">
<Label htmlFor="folder-name">{t('folders.name')}</Label>
<Input id="folder-name" name="name" maxLength={80} autoFocus required />
</div>
<div className="field">
<Label htmlFor="folder-description">{t('folders.description')}</Label>
<Textarea id="folder-description" name="description" maxLength={500} rows={2} />
</div>
<div className="grid gap-3 sm:grid-cols-2">
<div className="field">
<Label htmlFor="folder-cover-type">{t('folders.cover')}</Label>
<select
id="folder-cover-type"
className="field__select"
value={coverType}
onChange={(event) => {
setCoverType(event.target.value as typeof coverType);
setError(undefined);
}}
>
<option value="none">{t('folders.noCover')}</option>
<option value="emoji">{t('folders.emoji')}</option>
<option value="image">{t('folders.image')}</option>
</select>
</div>
{coverType === 'emoji' && (
<div className="field">
<Label htmlFor="folder-emoji">{t('folders.emoji')}</Label>
<Input id="folder-emoji" name="emoji" placeholder="🎁" maxLength={32} required />
</div>
)}
{coverType === 'image' && (
<div className="field">
<Label htmlFor="folder-cover-file">{t('folders.image')}</Label>
<Input id="folder-cover-file" name="cover" type="file" accept={coverTypes} required />
</div>
)}
</div>
{error && <p role="alert" className="field__error">{error}</p>}
<div className="flex flex-wrap gap-2">
<Button type="submit" disabled={create.isPending}>
<FolderPlus className="h-4 w-4" aria-hidden />
{t('folders.create')}
</Button>
<Button variant="ghost" onClick={onCancel} disabled={create.isPending}>
{t('common.cancel')}
</Button>
</div>
</form>
);
}
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { useRef } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { createWishSchema, type CreateWishInput, type Wish } from '@family-wishlist/shared';
import { createWishSchema, type CreateWishInput, type Wish, type WishFolder } from '@family-wishlist/shared';
import { Button } from '../ui/Button';
import { Input } from '../ui/Input';
import { Textarea } from '../ui/Textarea';
@@ -18,13 +18,14 @@ import {
import { translateValidation, useI18n } from '@/i18n/i18n';
interface Props {
open: boolean;
mode: 'create' | 'edit';
initial?: Wish;
folders?: WishFolder[];
defaultFolderId?: string;
onClose: () => void;
}
export function WishForm({ open, mode, initial, onClose }: Props) {
export function WishForm({ mode, initial, folders, defaultFolderId, onClose }: Props) {
const { t } = useI18n();
const create = useCreateWish();
const update = useUpdateWish();
@@ -33,12 +34,10 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
const resetImage = useResetWishImage();
const fileInputRef = useRef<HTMLInputElement>(null);
const [pendingId, setPendingId] = useState<string | null>(null);
const {
register,
handleSubmit,
reset,
formState: { errors, isSubmitting },
} = useForm<CreateWishInput>({
resolver: zodResolver(createWishSchema),
@@ -48,37 +47,29 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
currency: initial?.currency ?? 'RUB',
url: initial?.url ?? '',
comment: initial?.comment ?? '',
folderId: initial?.folderId ?? defaultFolderId ?? null,
},
});
useEffect(() => {
if (!open) return;
reset({
title: initial?.title ?? '',
price: initial?.price ?? '',
currency: initial?.currency ?? 'RUB',
url: initial?.url ?? '',
comment: initial?.comment ?? '',
});
setPendingId(initial?.id ?? null);
}, [open, initial, reset]);
const submit = handleSubmit(async (values) => {
if (mode === 'create') {
const created = await create.mutateAsync(values);
setPendingId(created.id);
} else if (initial) {
await update.mutateAsync({ id: initial.id, input: values });
const input = { ...values, folderId: folders ? values.folderId : undefined };
try {
if (mode === 'create') {
await create.mutateAsync(input);
} else if (initial) {
await update.mutateAsync({ id: initial.id, input });
}
onClose();
} catch {
// The mutation reports the error and the form retains the draft.
}
onClose();
});
const activeId = pendingId ?? initial?.id ?? null;
const canEditImage = activeId != null;
const activeId = initial?.id;
return (
<Modal
open={open}
open
onClose={onClose}
title={mode === 'create' ? t('wishForm.addTitle') : t('wishForm.editTitle')}
description={
@@ -102,12 +93,28 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
<form id="wish-form" className="grid gap-4" onSubmit={submit}>
<div className="field">
<Label htmlFor="title">{t('wishForm.title')}</Label>
<Input id="title" placeholder={t('wishForm.titlePlaceholder')} {...register('title')} />
<Input id="title" autoFocus placeholder={t('wishForm.titlePlaceholder')} {...register('title')} />
{errors.title && (
<span className="field__error">{translateValidation(t, errors.title.message)}</span>
)}
</div>
{folders && folders.length > 0 && (
<div className="field">
<Label htmlFor="wish-folder">{t('folders.field')}</Label>
<select
id="wish-folder"
className="field__select"
{...register('folderId', { setValueAs: (value) => value || null })}
>
<option value="">{t('folders.noFolder')}</option>
{folders.map((folder) => (
<option key={folder.id} value={folder.id}>{folder.name}</option>
))}
</select>
</div>
)}
<div className="grid gap-4 sm:grid-cols-[1fr_auto]">
<div className="field">
<Label htmlFor="price">{t('wishForm.price')}</Label>
@@ -153,7 +160,7 @@ export function WishForm({ open, mode, initial, onClose }: Props) {
</div>
</form>
{canEditImage && activeId && (
{activeId && (
<section className="mt-6 rounded-md border border-border bg-surface-muted p-4">
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-ink">
<ImageIcon className="h-4 w-4" />
@@ -1,11 +1,18 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type { CreateWishInput, UpdateWishInput } from '@family-wishlist/shared';
import type {
CreateFolderInput,
CreateWishInput,
UpdateWishInput,
WishDashboard,
WishFolder,
} from '@family-wishlist/shared';
import { toast } from 'sonner';
import { wishesApi, type OwnerStatus } from './wishes.api';
import { ApiError } from '@/lib/api';
import { api, ApiError } from '@/lib/api';
import { useI18n } from '@/i18n/i18n';
const LIST_KEY = (status: OwnerStatus) => ['wishes', status] as const;
const DASHBOARD_KEY = ['wishes', 'dashboard'] as const;
function invalidateAll(client: ReturnType<typeof useQueryClient>): void {
void client.invalidateQueries({ queryKey: ['wishes'] });
@@ -24,6 +31,36 @@ export function useWishes(status: OwnerStatus) {
});
}
export function useWishDashboard() {
return useQuery({
queryKey: DASHBOARD_KEY,
queryFn: ({ signal }) => api.get<WishDashboard>('/api/dashboard', signal),
});
}
export function useCreateFolder() {
const client = useQueryClient();
return useMutation({
mutationFn: ({ input, cover }: { input: CreateFolderInput; cover: File | null }) => {
const data = new FormData();
data.append('name', input.name);
if (input.description) data.append('description', input.description);
if (input.emoji) data.append('emoji', input.emoji);
if (cover) data.append('cover', cover);
return api.upload<WishFolder>('/api/folders', data);
},
onSuccess: (folder) => {
client.setQueryData<WishDashboard>(DASHBOARD_KEY, (current) =>
current && {
...current,
folders: [...current.folders.filter(({ id }) => id !== folder.id), folder],
},
);
void client.invalidateQueries({ queryKey: DASHBOARD_KEY });
},
});
}
export function useCreateWish() {
const client = useQueryClient();
const { t } = useI18n();
+40 -10
View File
@@ -29,7 +29,7 @@ const translations = {
'common.days.many': '{count} дней',
'footer.frontend': 'frontend v{version}',
'footer.backend': 'backend v{version}',
'header.active': 'Активные',
'header.home': 'Главная',
'header.fulfilled': 'Исполненные',
'header.archive': 'Архив',
'header.trash': 'Корзина',
@@ -44,12 +44,27 @@ const translations = {
'login.password': 'Пароль',
'login.submit': 'Войти',
'login.failed': 'Не удалось войти',
'dashboard.title': 'Ваш список желаний',
'dashboard.description': 'Добавляйте вещи, о которых мечтаете. Публичная страница доступна по адресу ',
'dashboard.title': 'Семейный список желаний',
'dashboard.publicPage': 'Моя публичная страница',
'dashboard.addWish': 'Добавить желание',
'dashboard.emptyTitle': 'Желаний пока нет',
'dashboard.emptyText': 'Начните с того, что вам действительно хочется получить.',
'dashboard.addFirstWish': 'Добавить первое желание',
'dashboard.loadError': 'Не удалось загрузить список желаний.',
'dashboard.retry': 'Повторить',
'folders.title': 'Папки желаний',
'folders.all': 'Все',
'folders.create': 'Создать папку',
'folders.name': 'Название',
'folders.description': 'Описание (необязательно)',
'folders.cover': 'Обложка',
'folders.noCover': 'Без обложки',
'folders.emoji': 'Эмодзи',
'folders.image': 'Изображение',
'folders.field': 'Папка',
'folders.noFolder': 'Без общей папки',
'folders.invalidDetails': 'Проверьте название и описание папки.',
'folders.invalidEmoji': 'Введите эмодзи для обложки.',
'folders.invalidImage': 'Выберите файл JPEG, PNG, WebP или GIF размером до 8 МБ.',
'folders.saveError': 'Не удалось создать папку. Попробуйте ещё раз.',
'archive.title': 'Архив',
'archive.description': 'Отложенные желания. Их видите только вы, и их можно вернуть в активный список.',
'archive.emptyTitle': 'Архив пуст',
@@ -146,7 +161,7 @@ const translations = {
'common.days.many': '{count} days',
'footer.frontend': 'frontend v{version}',
'footer.backend': 'backend v{version}',
'header.active': 'Active',
'header.home': 'Home',
'header.fulfilled': 'Fulfilled',
'header.archive': 'Archive',
'header.trash': 'Trash',
@@ -161,12 +176,27 @@ const translations = {
'login.password': 'Password',
'login.submit': 'Sign in',
'login.failed': 'Login failed',
'dashboard.title': 'Your wishlist',
'dashboard.description': 'Add things you dream of. Share your public page at ',
'dashboard.title': 'Family wishlist',
'dashboard.publicPage': 'My public page',
'dashboard.addWish': 'Add wish',
'dashboard.emptyTitle': 'No wishes yet',
'dashboard.emptyText': "Start by adding something you'd love to receive.",
'dashboard.addFirstWish': 'Add your first wish',
'dashboard.loadError': "Couldn't load wishes.",
'dashboard.retry': 'Try again',
'folders.title': 'Wish folders',
'folders.all': 'All',
'folders.create': 'Create folder',
'folders.name': 'Name',
'folders.description': 'Description (optional)',
'folders.cover': 'Cover',
'folders.noCover': 'No cover',
'folders.emoji': 'Emoji',
'folders.image': 'Image',
'folders.field': 'Folder',
'folders.noFolder': 'No shared folder',
'folders.invalidDetails': 'Check the folder name and description.',
'folders.invalidEmoji': 'Enter an emoji for the cover.',
'folders.invalidImage': 'Choose a JPEG, PNG, WebP, or GIF file up to 8 MB.',
'folders.saveError': "Couldn't create the folder. Try again.",
'archive.title': 'Archive',
'archive.description': 'Wishes you put aside. Only you see this. Restore them to your active list any time.',
'archive.emptyTitle': 'Archive is empty',
+194 -62
View File
@@ -1,104 +1,236 @@
import { useState } from 'react';
import { Plus, Sparkles } from 'lucide-react';
import { useRef, useState, type ReactNode } from 'react';
import { Folder, FolderPlus, LayoutGrid, Plus, UserRound } from 'lucide-react';
import type { Wish } from '@family-wishlist/shared';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/Button';
import { WishCard } from '@/components/WishCard/WishCard';
import { FolderForm } from '@/components/WishForm/FolderForm';
import { WishForm } from '@/components/WishForm/WishForm';
import {
useArchiveWish,
useCompleteWish,
useDeleteWish,
useWishes,
useDuplicateWish,
useWishDashboard,
} from '@/features/wishes/wishes.hooks';
import { useAuthStore } from '@/features/auth/authStore';
import { Link } from 'react-router-dom';
import { useI18n } from '@/i18n/i18n';
type Selection = { type: 'all' } | { type: 'author' | 'folder'; id: string };
function FolderButton({
label,
cover,
selected,
onClick,
}: {
label: string;
cover: ReactNode;
selected: boolean;
onClick: () => void;
}) {
return (
<Button
variant="outline"
aria-pressed={selected}
onClick={onClick}
className="wish-folders__item"
>
<span className="wish-folders__cover" aria-hidden="true">{cover}</span>
<span className="min-w-0 break-words text-left">{label}</span>
</Button>
);
}
export function DashboardPage() {
const { t } = useI18n();
const { data, isLoading } = useWishes('active');
const [creating, setCreating] = useState(false);
const { data, isPending, isError, refetch } = useWishDashboard();
const [selection, setSelection] = useState<Selection>({ type: 'all' });
const [creatingFolder, setCreatingFolder] = useState(false);
const [creatingWish, setCreatingWish] = useState(false);
const [editing, setEditing] = useState<Wish | null>(null);
const createFolderButton = useRef<HTMLButtonElement>(null);
const archive = useArchiveWish();
const complete = useCompleteWish();
const remove = useDeleteWish();
const user = useAuthStore((s) => s.user);
const duplicate = useDuplicateWish();
const user = useAuthStore((state) => state.user);
const selectedAuthor = selection.type === 'author'
? data?.authors.find(({ id }) => id === selection.id)
: undefined;
const selectedFolder = selection.type === 'folder'
? data?.folders.find(({ id }) => id === selection.id)
: undefined;
const wishes = data?.wishes.filter((wish) =>
selectedAuthor ? wish.userId === selectedAuthor.id
: selectedFolder ? wish.folderId === selectedFolder.id
: true,
);
const canAddWish = !selectedAuthor || selectedAuthor.id === user?.id;
const sectionTitle = selectedAuthor?.displayName ?? selectedFolder?.name ?? t('folders.all');
function closeFolderForm() {
setCreatingFolder(false);
createFolderButton.current?.focus();
}
return (
<div className="grid gap-6">
<section className="page-section flex flex-wrap items-end justify-between gap-4">
<div>
<h1 className="page-section__title">{t('dashboard.title')}</h1>
<p className="page-section__text">
{t('dashboard.description')}
{user && (
<Link
to={`/u/${user.slug}`}
className="font-medium text-primary hover:text-primary-600"
>
/u/{user.slug}
</Link>
)}
.
</p>
{user && (
<Link
to={`/u/${user.slug}`}
className="mt-1 inline-block text-sm font-medium text-ink underline underline-offset-4 hover:decoration-primary"
>
{t('dashboard.publicPage')}
</Link>
)}
</div>
<Button size="lg" onClick={() => setCreating(true)}>
<Plus className="h-4 w-4" />
{t('dashboard.addWish')}
</Button>
</section>
{isLoading && (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{[0, 1, 2].map((i) => (
<div
key={i}
className="wish-card animate-pulse"
style={{ minHeight: 320, background: 'rgb(var(--color-surface-muted))' }}
{data && (
<section className="wish-folders" aria-label={t('folders.title')}>
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="font-semibold text-ink">{t('folders.title')}</h2>
<Button
ref={createFolderButton}
variant="ghost"
aria-expanded={creatingFolder}
onClick={() => setCreatingFolder(true)}
>
<FolderPlus className="h-4 w-4" aria-hidden />
{t('folders.create')}
</Button>
</div>
<div className="wish-folders__list">
<FolderButton
label={t('folders.all')}
cover={<LayoutGrid className="h-4 w-4" />}
selected={!selectedAuthor && !selectedFolder}
onClick={() => setSelection({ type: 'all' })}
/>
{data.authors.map((author) => (
<FolderButton
key={author.id}
label={author.displayName}
cover={author.avatarUrl
? <img src={author.avatarUrl} alt="" />
: <UserRound className="h-4 w-4" />}
selected={selectedAuthor?.id === author.id}
onClick={() => setSelection({ type: 'author', id: author.id })}
/>
))}
{data.folders.map((folder) => (
<FolderButton
key={folder.id}
label={folder.name}
cover={folder.imageUrl
? <img src={folder.imageUrl} alt="" loading="lazy" />
: folder.emoji ?? <Folder className="h-4 w-4" />}
selected={selectedFolder?.id === folder.id}
onClick={() => setSelection({ type: 'folder', id: folder.id })}
/>
))}
</div>
{creatingFolder && (
<FolderForm
onCancel={closeFolderForm}
onCreated={(folder) => {
setSelection({ type: 'folder', id: folder.id });
closeFolderForm();
}}
/>
)}
</section>
)}
{isPending && (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3" aria-busy="true">
{[0, 1, 2].map((i) => (
<div key={i} className="wish-card min-h-80 animate-pulse bg-surface-muted" />
))}
</div>
)}
{!isLoading && data && data.length === 0 && (
{isError && (
<div className="empty-state gap-4">
<img src="/empty-state.svg" alt="" className="empty-state__icon--image" />
<div>
<h2 className="empty-state__title">{t('dashboard.emptyTitle')}</h2>
<p className="empty-state__text mt-1">
{t('dashboard.emptyText')}
</p>
</div>
<Button onClick={() => setCreating(true)}>
<Sparkles className="h-4 w-4" />
{t('dashboard.addFirstWish')}
<p role="alert" className="empty-state__text">{t('dashboard.loadError')}</p>
<Button variant="outline" onClick={() => void refetch()}>
{t('dashboard.retry')}
</Button>
</div>
)}
{!isLoading && data && data.length > 0 && (
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
{data.map((wish) => (
<WishCard
key={wish.id}
wish={wish}
view="owner"
onEdit={() => setEditing(wish)}
onArchive={() => archive.mutate(wish.id)}
onComplete={() => complete.mutate(wish.id)}
onDelete={() => remove.mutate(wish.id)}
/>
))}
</div>
{wishes && (
<section className="grid min-w-0 gap-4" aria-label={sectionTitle}>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0">
<h2 className="break-words text-xl font-semibold text-ink">{sectionTitle}</h2>
{selectedFolder?.description && (
<p className="mt-1 whitespace-pre-wrap break-words text-sm text-muted">
{selectedFolder.description}
</p>
)}
</div>
{canAddWish && (
<Button onClick={() => setCreatingWish(true)}>
<Plus className="h-4 w-4" aria-hidden />
{t('dashboard.addWish')}
</Button>
)}
</div>
{wishes.length === 0 ? (
<div className="empty-state">
<img src="/empty-state.svg" alt="" className="empty-state__icon--image" />
<h3 className="empty-state__title">{t('dashboard.emptyTitle')}</h3>
</div>
) : (
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
{wishes.map((wish) => {
const owned = wish.userId === user?.id;
const author = data?.authors.find(({ id }) => id === wish.userId);
return (
<WishCard
key={wish.id}
wish={wish}
view={owned ? 'owner' : 'guest'}
onEdit={() => setEditing(wish)}
onArchive={() => archive.mutate(wish.id)}
onComplete={() => complete.mutate(wish.id)}
onDelete={() => remove.mutate(wish.id)}
onDuplicate={() => duplicate.mutate(wish.id)}
footer={!selectedAuthor && author && (
<p className="mt-auto break-words pt-2 text-xs text-muted">
{author.displayName}
</p>
)}
/>
);
})}
</div>
)}
</section>
)}
<WishForm open={creating} mode="create" onClose={() => setCreating(false)} />
<WishForm
open={editing !== null}
mode="edit"
initial={editing ?? undefined}
onClose={() => setEditing(null)}
/>
{creatingWish && (
<WishForm
mode="create"
folders={data?.folders}
defaultFolderId={selectedFolder?.id}
onClose={() => setCreatingWish(false)}
/>
)}
{editing && (
<WishForm
mode="edit"
initial={editing}
folders={data?.folders}
onClose={() => setEditing(null)}
/>
)}
</div>
);
}
+22
View File
@@ -131,6 +131,28 @@
@apply text-sm text-muted;
}
.wish-folders {
@apply grid min-w-0 gap-3 border-b border-border pb-5;
}
.wish-folders__list {
@apply flex flex-wrap gap-2;
}
.wish-folders .wish-folders__item {
@apply h-auto min-h-11 max-w-full justify-start px-2.5 py-1.5 pr-3;
}
.wish-folders__item[aria-pressed='true'] {
@apply border-primary bg-primary/10 text-ink;
}
.wish-folders__cover {
@apply grid h-7 w-7 shrink-0 place-items-center overflow-hidden rounded-sm bg-surface-muted text-base;
}
.wish-folders__cover img {
@apply h-full w-full object-cover;
}
.wish-folders__form {
@apply grid min-w-0 max-w-xl gap-4 rounded-md border border-border bg-surface p-4;
}
.public-profile {
@apply flex min-h-screen flex-col;
}
+1 -1
View File
@@ -49,4 +49,4 @@ WORKDIR /app/apps/backend
EXPOSE 3000
# Apply schema (idempotent; uses `db push` so no prior migrations required) +
# seed env users + start server.
CMD ["sh", "-c", "pnpm exec prisma db push --accept-data-loss --skip-generate && node dist/prisma/seed.js && node dist/src/index.js"]
CMD ["sh", "-c", "pnpm exec prisma db push --skip-generate && node dist/prisma/seed.js && node dist/src/index.js"]
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@family-wishlist/shared",
"version": "0.3.0",
"version": "0.4.0",
"private": true,
"type": "module",
"main": "./dist/index.js",
+29
View File
@@ -0,0 +1,29 @@
import { z } from 'zod';
import type { Wish } from './wish.schema.js';
export const createFolderSchema = z.object({
name: z.string().trim().min(1).max(80),
description: z.string().trim().max(500).optional(),
emoji: z
.string()
.trim()
.max(32)
.regex(/^(?:(?:\p{Extended_Pictographic}|\p{Regional_Indicator})[\p{Extended_Pictographic}\p{Regional_Indicator}\p{Emoji_Modifier}\uFE0F\u200D]*|[#*0-9]\uFE0F?\u20E3)$/u)
.optional(),
});
export type CreateFolderInput = z.infer<typeof createFolderSchema>;
export interface WishFolder {
id: string;
name: string;
description: string | null;
emoji: string | null;
imageUrl: string | null;
}
export interface WishDashboard {
authors: { id: string; displayName: string; avatarUrl: string | null }[];
folders: WishFolder[];
wishes: (Wish & { userId: string; isNewForOwner: boolean })[];
}
+1
View File
@@ -1,5 +1,6 @@
export * from './auth.schema.js';
export * from './profile.schema.js';
export * from './wish.schema.js';
export * from './folder.schema.js';
export * from './public.schema.js';
export * from './types.js';
+2
View File
@@ -22,12 +22,14 @@ export const wishSchema = z.object({
completedAt: z.string().nullable(),
deletedAt: z.string().nullable(),
sourceWishId: z.string().nullable(),
folderId: z.string().nullable().optional(),
isNewForGuest: z.boolean().optional(),
});
export type Wish = z.infer<typeof wishSchema>;
export const createWishSchema = z.object({
folderId: z.string().cuid().nullable().optional(),
title: z.string().trim().min(1).max(200),
price: z
.union([