From e9b2f76ee3c7765ef319ad113a51a93e3af2fa68 Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 17 Nov 2026 20:45:02 +0000 Subject: [PATCH 1/3] Add shared wish folders and family dashboard --- README.md | 10 +- apps/backend/package.json | 2 +- apps/backend/prisma/schema.prisma | 16 ++ apps/backend/src/app.ts | 2 + .../src/modules/public/public.routes.ts | 2 +- .../src/modules/wishes/dashboard.routes.ts | 100 +++++++ .../src/modules/wishes/wishes.service.ts | 13 +- apps/frontend/package.json | 2 +- .../frontend/src/components/Layout/Header.tsx | 4 +- .../src/components/WishForm/FolderForm.tsx | 107 ++++++++ .../src/components/WishForm/WishForm.tsx | 65 +++-- .../src/features/wishes/wishes.hooks.ts | 41 ++- apps/frontend/src/i18n/i18n.tsx | 50 +++- apps/frontend/src/pages/DashboardPage.tsx | 256 +++++++++++++----- apps/frontend/src/styles/global.css | 22 ++ packages/shared/package.json | 2 +- packages/shared/src/folder.schema.ts | 29 ++ packages/shared/src/index.ts | 1 + packages/shared/src/wish.schema.ts | 2 + 19 files changed, 613 insertions(+), 113 deletions(-) create mode 100644 apps/backend/src/modules/wishes/dashboard.routes.ts create mode 100644 apps/frontend/src/components/WishForm/FolderForm.tsx create mode 100644 packages/shared/src/folder.schema.ts diff --git a/README.md b/README.md index e9b3026..74cc35a 100644 --- a/README.md +++ b/README.md @@ -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/` 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/` 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 @@ -203,6 +205,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. | @@ -240,7 +244,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. diff --git a/apps/backend/package.json b/apps/backend/package.json index b31e5f0..becd477 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -1,6 +1,6 @@ { "name": "@family-wishlist/backend", - "version": "0.3.0", + "version": "0.4.0", "private": true, "type": "module", "main": "dist/index.js", diff --git a/apps/backend/prisma/schema.prisma b/apps/backend/prisma/schema.prisma index 7344d3a..455ddbf 100644 --- a/apps/backend/prisma/schema.prisma +++ b/apps/backend/prisma/schema.prisma @@ -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 { diff --git a/apps/backend/src/app.ts b/apps/backend/src/app.ts index 6220d62..0d935b6 100644 --- a/apps/backend/src/app.ts +++ b/apps/backend/src/app.ts @@ -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 { 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' }); diff --git a/apps/backend/src/modules/public/public.routes.ts b/apps/backend/src/modules/public/public.routes.ts index 0d670f0..67ed321 100644 --- a/apps/backend/src/modules/public/public.routes.ts +++ b/apps/backend/src/modules/public/public.routes.ts @@ -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), })); diff --git a/apps/backend/src/modules/wishes/dashboard.routes.ts b/apps/backend/src/modules/wishes/dashboard.routes.ts new file mode 100644 index 0000000..41255d0 --- /dev/null +++ b/apps/backend/src/modules/wishes/dashboard.routes.ts @@ -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 = {}; + 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; + } + }); +} diff --git a/apps/backend/src/modules/wishes/wishes.service.ts b/apps/backend/src/modules/wishes/wishes.service.ts index a5702c4..4f84720 100644 --- a/apps/backend/src/modules/wishes/wishes.service.ts +++ b/apps/backend/src/modules/wishes/wishes.service.ts @@ -32,10 +32,18 @@ export class WishesService { return wish; } - create(userId: string, input: CreateWishInput): Promise { + private async checkFolder(folderId: string | null | undefined): Promise { + if (folderId && !(await this.prisma.wishFolder.findUnique({ where: { id: folderId } }))) { + throw new NotFoundError('Folder'); + } + } + + async create(userId: string, input: CreateWishInput): Promise { + 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 { await this.getOwned(userId, id); + await this.checkFolder(input.folderId); const data: Record = {}; + 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, }, }); } diff --git a/apps/frontend/package.json b/apps/frontend/package.json index 903a79f..3882a91 100644 --- a/apps/frontend/package.json +++ b/apps/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@family-wishlist/frontend", - "version": "0.3.4", + "version": "0.4.0", "private": true, "type": "module", "scripts": { diff --git a/apps/frontend/src/components/Layout/Header.tsx b/apps/frontend/src/components/Layout/Header.tsx index c184097..860a0e4 100644 --- a/apps/frontend/src/components/Layout/Header.tsx +++ b/apps/frontend/src/components/Layout/Header.tsx @@ -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 }, diff --git a/apps/frontend/src/components/WishForm/FolderForm.tsx b/apps/frontend/src/components/WishForm/FolderForm.tsx new file mode 100644 index 0000000..8e42264 --- /dev/null +++ b/apps/frontend/src/components/WishForm/FolderForm.tsx @@ -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(); + + async function submit(event: FormEvent) { + 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 ( +
+
+ + +
+
+ +